liveBook · Manning

_ViewImports.cshtml

As explained in ASP.NET Core in Action, 3e

_ViewImports.cshtml is a conventionally named Razor file whose directives and imports are implicitly applied to Razor views and pages in its directory and descendant directories.

_ViewImports.cshtml centralizes Razor directives that would otherwise be repeated across views and pages. Place it in a folder to apply its directives to views and subfolders; placing it in the root Pages folder commonly covers the application’s Razor Pages and partial views. section 17.4.4

Use _ViewImports.cshtml for shared Razor directives, not arbitrary application code:

  • Import namespaces with directives such as @using, so views can reference application types without repeating namespace declarations. section 17.4.4
  • Share other Razor directives, including @model and @addTagHelper, across the applicable views. section 17.4.4
  • Keep executable C# elsewhere: _ViewImports.cshtml accepts Razor directives, while _ViewStart.cshtml is used for common view-start code such as setting Layout. section 17.4.4
  • Apply files hierarchically: root-folder files execute first, followed by files in more specific controller or view folders. section 17.5

Typical shared imports

A typical file imports application namespaces and enables the built-in Tag Helpers: @using WebApplication1, @using WebApplication1.Pages, @using WebApplication1.Models, and @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers.

Registering a custom Tag Helper

Register a custom Tag Helper with @addTagHelper CustomTagHelpers.SystemInfoTagHelper, CustomTagHelpers, or register every Tag Helper in the assembly with @addTagHelper *, CustomTagHelpers. The registered helper then becomes available in Razor views, partial views, and layouts. section 32.1.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines supported directives, placement, hierarchy, and the boundary with _ViewStart.cshtml, but does not execute arbitrary C#.
Examples
Uses namespace imports, built-in Tag Helpers, and custom Tag Helper registration as concrete configuration examples.
What it assumes
Assumes familiarity with Razor views or pages and distinguishes directive imports from executable view-start code.
What you can do after
Configure shared Razor namespaces and Tag Helpers without repeating directives in individual views.
How it connects
Connects Razor directives, Razor Pages, partial views, layouts, Tag Helpers, and _ViewStart.cshtml.

Also explained in

Compare how 2 books explain _ViewImports.cshtml →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.