ViewImports in ASP.NET Core MVC

ViewImports in ASP.NET Core MVC

In this article, I will discuss ViewImports in an 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. ASP.NET Core MVC and Razor come with many new advanced features for working with 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 Application?
  2. Example to Understand ViewImports in ASP.NET Core MVC.
  3. _ViewImports file Hierarchical Order in ASP.NET Core MVC.
  4. When to Use _ViewImports.cshtml in ASP.NET Core MVC?
What is _ViewImports.cshtml in ASP.NET Core MVC Application?

The _ViewImports.cshtml in ASP.NET Core MVC is a special file that enables us to add common namespaces, directives, and other elements to multiple views without having to add these namespaces, directives, and other elements to every individual view file. The common namespaces, directives, and other elements present in the _ViewImports.cshtml file are then automatically applied to all Razor views in the same directory or subdirectories. The following are the things that can be placed in the _ViewImports.cshtml file:

  • Namespaces: You can add @using directives for namespaces that you want to be available in your views. For example, if you have models or data access layer code that you frequently reference in your views, you can include these namespaces in _ViewImports.cshtml to make them universally accessible without adding @using in each individual view.
  • Tag Helpers: The @addTagHelper directive allows you to make tag helpers available across all views. This is useful for frequently used tag helpers, such as those provided by ASP.NET Core itself or any custom tag helpers you have developed.
  • View Layouts: By specifying the @layout directive in _ViewImports.cshtml, you can define a default layout for all views in the folder. This can be overridden in specific views if needed.

Note: In this article, I will show you how to use the @using directive in the ViewImports.cshtml file. We will discuss the rest of the directives in our upcoming articles.

Example to Understand ViewImports in ASP.NET Core MVC:

Create a class file named Student.cs within the Models folder and then copy and paste the following code. 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, 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 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 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: When creating the project using the ASP.NET Core Web Application using the Model-View-Controller Project template, Visual Studio adds the _ViewImports.cshtml file with the Views Folder by default. 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 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. The following are the places where you can place the _ViewImports file in ASP.NET Core MVC:

  • Application Level: The root level of the application is the most general level where a _ViewImports.cshtml file can be placed. Located in the Views folder, directives placed here are globally available to all views throughout the application. This is the highest level in the hierarchy.
  • Area Level: If your application is structured using Areas to group related functionalities, each area can have its own _ViewImports.cshtml file. This file is located within the Areas/[AreaName]/Views directory. Directives here apply to all views within the specified area, overriding or augmenting directives from the application level.
  • Controller Level: Within each area or the root Views directory, the controller-specific _ViewImports.cshtml can be placed inside the Views/[ControllerName] directory. This targets all views associated with the specified controller, allowing for controller-specific namespaces or tag helpers.
  • View Level: The most specific level is directly within a specific view file. This allows for more control over directives that apply only to a particular view.

Please have a look at the image below to better understand. Here, we have one ViewImports file in the Views folder and another 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. 

How Does It Work?

When rendering a view, ASP.NET Core MVC processes _ViewImports.cshtml files from the most general to the most specific. This means that directives defined at the application level are applied first, followed by those at the area level, then the controller level, and finally at the view level. If the same directive is defined at multiple levels, the most specific definition takes precedence. This hierarchical processing ensures that common settings can be defined globally while allowing for specific overrides where needed.

In the next article, I will discuss Partial Views in ASP.NET Core MVC Applications. Here, in this article, I explain 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 *