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 one, as it is a continuation 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 come 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 in ASP.NET Core MVC?
  2. Understanding ViewImports with an example.
  3. Creating ViewImports.cshtml file in ASP.NET Core MVC Application.
  4. Understanding the Hierarchical Order of ViewImports file in ASP.NET Core MVC.
What is _ViewImports.cshtml in ASP.NET Core MVC Application?

In ASP.NET Core MVC, the ViewImports file (_ViewImports.cshtml) is a special Razor view file that allows us to specify the common namespaces, directives, and other elements, that will be automatically imported and applied to all views within a specific directory and its subdirectories. It helps us to simplify the Razor syntax and reduce repetitive code by centralizing the import statements in one place.

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 on each and every page. At this point in time, 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 Tag Helpers. The @namespace directive is used to specify the namespace the ViewImports belongs to. With the help of the @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 page.

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

Example to Understand ViewImports in ASP.NET Core MVC:

Create a model class file with the name Student.cs within the Models folder of your application. Once you create the Students.cs class file, please copy and paste the following code into it. As you can see, we have created the Student model with five properties. 

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; }
    }
}
Modifying Home Controller:

Next, modify the Home Controller as shown below. As you can see, here we have created two action methods. The Index Action Method displays all the student data, while the Details Action Method takes the student id as a parameter and returns that student information.

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);
        }
    }
}
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 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 like the _ViewStart.cshtml file. To create the _ViewImports.cshtml file, right-click on the Views folder and then select the Add – New Item option from the context menu, which will open the “New Item” window. From the New Item window, search for Razor, select the Razor View Import, and click on the Add button as shown in the image below, which should create the _ViewImport.cshtml within the Views folder.

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

Note: By creating the project using ASP.NET Core Web Application using Model-View-Controller Project template, by default, Visual Studio adds the _ViewImports.cshtml file with the Views Folder. Once the _ViewImports.cshtml file is created, copy and paste the following code.

@using FirstCoreMVCApplication.Models;

As we placed the above namespace in the ViewImports file, all the types present in the above namespace are available to every view of our application. So now we don’t need to type the Type’s fully qualified name. 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 specifying the model name. Run the application, and it should work as expected.

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

Like the _ViewStart file, the _ViewImports file is 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 file is Hierarchical Order in ASP.NET Core MVC

The settings specified in the _ViewImports file 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. _ViewImports.cshtml is useful for organizing and modularizing your codebase. You can define different _ViewImports.cshtml files in different directories to apply different sets of namespaces and directives based on the functionality and purpose of each section of your application.

By using _ViewImports.cshtml, you can simplify your views by avoiding repetitive @using directives and also promoting a consistent structure and design across your ASP.NET Core MVC application.

In the next article, I am going to discuss the Partial Views in ASP.NET Core MVC Applications. Here, in this article, I try to explain the ViewImports in ASP.NET Core MVC Application.

1 thought on “ViewImports in ASP.NET Core MVC”

Leave a Reply

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