(C# ASP.NET Core) _ViewImports file and the do's and don'ts

_ViewImports.cshtml is shared by all the razor pages in its peer directory, and in the sub-directories below it. It is like an include file, and it is used to type a list of common directives that would otherwise have to be typed in each of the razor pages. A razor page takes into account the entire hierarchy of _ViewImports files above it.

Categories | About |     |  


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








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.

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.