ViewImports in ASP.NET Core MVC

ViewImports in ASP.NET Core MVC

In this article, I am going to discuss the ViewImports in ASP.NET Core MVC Application. Please read our previous article before proceeding to this article as it is a continuation part of our previous article where we discussed the ViewStart in Layout Page in ASP.NET Core MVC Application. The ASP.NET Core MVC and Razor comes with a lot of new advanced features for working with the Razor views. ViewImports is one of the new features. As part of this article, we are going to discuss the following pointers.

  1. What is _ViewImports.cshtml?
  2. Understanding ViewImports with an example.
  3. Creating ViewImports.cshtml file in ASP.NET Core MVC Application.
  4. ViewImports file is hierarchical Order in ASP.NET Core MVC.
What is _ViewImports.cshtml in ASP.NET Core MVC Application?

In ASP.NET Core MVC Application, the _ViewImports.cshtml file provides a mechanism to include the directives globally for Razor Pages so that we don’t have to add them individually in each and every page. As of this article, the _ViewImports.cshtml file supports the following directives:

  1. @addTagHelper
  2. @tagHelperPrefix
  3. @removeTagHelper
  4. @namespace
  5. @inject
  6. @model
  7. @using

The @addTagHelper, @tagHelperPrefix, and @removeTagHelper directives are basically used to manage of Tag Helpers. The @namespace directive is basically used to specify the namespace that the ViewImports belongs to. With the help of @inject directive it supports Dependency injection. We already use the @model directive in our previous applications when we are working with models. The @model directive is basically used to specify the Model for your view. The @using directive basically used to include the common namespaces globally so that you don’t have to include the namespaces in each and every view pages.

Note: In this article, I am going to show you the use of @using directive in ViewImports.cshtml file. Rest directives are going to be discussing in our upcoming articles.

Let us understand ViewImports with an example:

Create a model called Students within the Models folder of your application. Once you create the Students.cs class file then copy and paste the following code in it.

namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
        public string Section { get; set; }
        public string Gender { get; set; }
    }
}

As you can see, here we created the student model with five properties. 

Modifying the Home Controller:

Modify the Home Controller as shown below.

using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            List<Student> listStudents = new List<Student>()
            {
               new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male" },
               new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female" },
               new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female" }
            };

            return View(listStudents);
        }

        public ViewResult Details(int Id)
        {
            var studentDetails = new Student() { StudentId = Id, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" };

            return View(studentDetails);
        }
    }
}

As you can see, here we have two action methods. One action method is used to display all the student data while the other action method takes the student id as a parameter and return that student information.

Modifying the Index and Details view:

Index.cshtml:

@model List<FirstCoreMVCApplication.Models.Student>
@{
    Layout = null;
}
<html>
<head>
    <title>Index</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Branch</th>
                <th>Section</th>
                <th>Gender</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>
                        @student.StudentId
                    </td>
                    <td>
                        @student.Name
                    </td>
                    <td>
                        @student.Branch
                    </td>
                    <td>
                        @student.Section
                    </td>
                    <td>
                        @student.Gender
                    </td>
                </tr>
            }
        </tbody>
    </table>
   </body>
</html>

Details.cshtml:

@model FirstCoreMVCApplication.Models.Student
@{
    Layout = null;
}
<html>
<head>
    <title>Student Detaills</title>
</head>
<body>
    <div>
        StudentId : @Model.StudentId
    </div>
    <div>
        Name : @Model.Name
    </div>
    <div>
        Branch : @Model.Branch
    </div>
    <div>
        Section : @Model.Section
    </div>
    <div>
        Gender : @Model.Gender
    </div>
</body>
</html>

In the above Index and Details view, we are using the @model directive to specify the model for the view. If you notice, then you can see in both the views we have specified the fully qualified name for the model such as “FirstCoreMVCApplication.Models.Student”. Now let us see how to move the namespace to the ViewImports file so that we can only specify the model name.

Creating ViewImports.cshtml file in ASP.NET Core MVC Application:

In general, _ViewImports.cshtml files are created within the Views or within the subfolder of the Views folder. To create the “_ViewImports.cshtml” file right-click on the Views folder and then select “Add – New Item” option from the context menu, which will open the “New Item” window. From the “New Item” window search for “Razor” and then select the “Razor View Import” and click on the “Add” button as shown in the below image which should create the “_ViewImport.cshtml” within the “Views” folder.

Creating ViewImports.cshtml file in ASP.NET Core MVC Application

Once the _ViewImports.cshtml file is created, then copy and paste the following code in it.

@using FirstCoreMVCApplication.Models;

As we placed the above namespace in the ViewImports file, now all the types that are present in the above namespace are available to each and every view in the “Home” folder. So now we don’t need to type the fully qualified name of the Type. So, modify the Index and Details view as shown below.

ViewImports in ASP.NET Core MVC

As you can see in the above image, we are removing the namespace and only specified the model name. Run the application and it should work as expected.

_ViewImports file is hierarchical Order in ASP.NET Core MVC:

Just like the _ViewStart file, the _ViewImports file is also hierarchical. It is also possible to pace the _ViewImports in the subfolder of the Views folder as shown in the below image. Here we have one _ViewImports file in the Views folder and another _ViewImports file within the Home folder.

_ViewImports.cshtml in ASP.NET Core MVC

The settings that are specified in the _ViewImports file present in the Home subfolder will overwrite the settings specified in the _ViewImports file in the Views folder. 

Note: If you specified a setting in the view itself, then that setting overrides the matching settings specified in the parent _ViewImports files in the folder hierarchy.

In the next article, I am going to discuss How to Install and use Bootstrap in ASP.NET Core MVC Application. Here, in this article, I try to explain the ViewImports in ASP.NET Core MVC Application.

Leave a Reply

Your email address will not be published. Required fields are marked *