Why do we need a _ViewImports?
Suppose you have 10 razor pages in the "Pages" folder, and each contains the same two lines for @model
and @using
directives.
There is a repetition of 10 x 2 = 20 lines?
This can be avoided by writing the two lines just once in a _ViewImports.cshtml file and place it along the 10 razor pages in their "Pages" folder so that the "Pages" folder now contains 10 + 1 = 11 files, but 18 fewer lines. Nothing else needs to be done.
ASP.NET Core engine treats as if those two lines were written inside each of the razor pages.
Benefit 1: Some modularity is achieved.
Benefit 2: Typing is saved.
Benefit 3: Razor pages become smaller, become readable because it is quicker to locate the code of relevance.
Which directives are supported?
The following directives can be included in a _ViewImports.cshtml file
@addTagHelper @removeTagHelper @tagHelperPrefix @using @model @inherits @inject
Video Explanation with a Working Example
Please watch the following youtube video:
What cannot be included?
Functions cannot be written inside this file.
Where should _ViewImports not be placed?
DO NOT place this file in the Shared folders such as /Pages/Shared. It is not usually done because the directives get applied to a wider set of pages, and clashes can occur, leading to compilation errors.
How many possible?
There is no limit to the number of _ViewImports files, but they must be used judiciously. Sub-folders can contain their own _ViewImports. A razor page itself can contain additional directives specific to it. The whole hierarchy of _ViewImports is evaluated for a page. So the deeper you take it, the more un-predictable could the things become.
Practical Recommendations?
The best use case for day to day projects would be to use them for minimizing the typing required for @using
, @namespace
and @addTagHelper
.
// example of _ViewImports.cshtml file // Pages > _ViewImports.cshtml @using MyFirstApp.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
The above is an example of a view imports file that makes a reference to a namespace, and also adds a addTagHelper directive so that it can be accessed by all razor pages adjacent to it.
This Blog Post/Article "(C# ASP.NET Core) _ViewImports file and the do's and don'ts" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.