• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Saturday, September 5, 2020

ViewImports in ASP.NET Core MVC

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

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. 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 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 page.

Note: In this article, I am going to show you the use of the @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 the “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.

Summary:
I hope this post will be helpful to understand the concept of ViewImports in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape