liveBook · Manning

_ViewStart.cshtml

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

_ViewStart.cshtml is a conventionally named Razor file containing code that executes before Razor views or pages in its directory and descendant directories are rendered.

_ViewStart.cshtml is a conventionally named Razor file that runs common Razor code before pages in its directory and descendant directories execute. Its usual job is assigning a default layout, so individual pages do not repeat the same Layout setting. section 17.4.4 section 17.5

@{
   Layout = "_Layout";
}

Place this code in Pages/_ViewStart.cshtml to apply _Layout as the default layout for Razor Pages beneath Pages. section 17.4.4

Use _ViewStart.cshtml to centralize presentation behavior while keeping local exceptions possible:

  • Put it in the Pages folder to affect all Razor Pages below that folder. section 17.4.4
  • Override the default layout in an individual Razor Page when that page needs a different layout. section 17.4.4
  • Use _ViewImports.cshtml for directives such as @using; use _ViewStart.cshtml for executable Razor code. section 17.4.4
  • Remember that it does not execute for layouts or partial views, and that hierarchical files execute from root folders toward more specific view folders. section 17.5

Sharing an application layout with Identity pages

Create Areas/Identity/Pages/_ViewStart.cshtml and set Layout = "/Pages/Shared/_Layout.cshtml". Identity Razor Pages then use the same base layout as the rest of the application. section 23.4.3

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

How deep it goes
Explains placement, inheritance, overrides, and execution boundaries, but does not detail the underlying Razor processing pipeline.
Examples
Demonstrates a default _Layout assignment and an area-specific layout for Identity Razor Pages.
What it assumes
Assumes familiarity with Razor Pages and layouts while distinguishing executable Razor code from imported directives.
What you can do after
Operate/configure Razor Pages with shared layouts and page-level layout exceptions.
How it connects
Connects _ViewStart.cshtml with Razor Pages, layouts, partial views, and _ViewImports.cshtml.

Also explained in

Compare how 2 books explain _ViewStart.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.