What are _ViewStart.cshtml and _ViewImports.cshtml for?

ASP.NET MVC Views & Razor Basic Fresher1–2 Yrs Conceptual 1 min read

Quick Answer

_ViewStart.cshtml runs before every view in its folder tree — its main job is Layout = "_Layout"; so you don't set it in each view. _ViewImports.cshtml holds shared directives — @using, @inject, and @addTagHelper registrations — applied to every view in the tree.

_ViewStart is code that runs before each view, and it's mostly there to set the default layout once instead of in every single view. _ViewImports is for shared directives — the @using statements for your namespaces, any @inject, and the @addTagHelper registration that turns tag helpers on. Both are hierarchical, so a subfolder can have its own that adds to or overrides the root ones, and any individual view can override the layout _ViewStart set.

  • Both cascade: a folder can have its own to override or add to the root one.
  • Override the layout in a specific view: @{ Layout = null; } or point to another file.
  • _ViewImports is where @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers lives, plus your project's namespaces so views don't need per-file @using.