In an ASP.NET Core MVC site, how do _ViewStart, _Layout, RenderBody and RenderSection give every listing page one layout with page-specific scripts?
answer
- _ViewStart sets Layout before each full view
- RenderBody marks where the view goes
- RenderSectionAsync("Scripts", required: false)
- @section Scripts { } in the view
- defined but unrendered section throws
basics
~10 s_ViewStart.cshtml sets Layout = "_Layout" for every full view; the layout calls RenderBody() where the view's content goes and RenderSectionAsync("Scripts", required: false) where a view's @section Scripts block goes.
solid answer
~50 s`_ViewStart.cshtml` runs before every full view (not partials) and typically sets `Layout = "_Layout"`; files are hierarchical, the root one first and the closest last, so a subfolder can switch layouts. The engine finds `_Layout` like a partial: the controller's folder, then `Views/Shared`. The layout calls `RenderBody()` where the view's output goes; a layout that neither renders nor ignores the body (`IgnoreBody()`) makes MVC throw. For page-specific markup the layout declares sections: `@await RenderSectionAsync("Scripts", required: false)` near `</body>`, and a listing page adds `@section Scripts { <script src="~/js/map.js"></script> }`. A section defined by the view but not rendered by the layout throws, unless the layout calls `IgnoreSection`; a required section the view doesn't define throws too. Sections reach only the immediate layout. `_ViewImports.cshtml` is the other special file: it holds directives such as `@using` and `@addTagHelper`, not code that runs.
code
razor · 9 lines@model ListingMapViewModel
@{
ViewData["Title"] = $"Map: {Model.Neighbourhood}";
}
<div id="map" data-lat="@Model.Latitude" data-lng="@Model.Longitude"></div>
@section Scripts {
<script src="~/js/listing-map.js"></script>
}go deeper
Recall that _ViewStart sets the layout, the layout calls RenderBody for the view's content, and views add page scripts with @section Scripts.
Explain the render order (view first, then layout), how _ViewStart files cascade, why RenderSection is required by default, and how _ViewImports differs.
Prevent broken pages from section mismatches with optional sections, IsSectionDefined fallbacks and per-folder _ViewStart overrides for print or admin layouts.
Define a small, stable layout contract (sections and ViewData keys) that every team's views can rely on as the site grows.
## The pieces A real-estate listings site wants one header, footer and stylesheet on every page, while the map page and the mortgage-calculator page each load their own script. ASP.NET Core MVC provides four pieces for that: - **`_Layout.cshtml`**, usually in `Views/Shared`: the page shell. It is a normal Razor view whose job is to wrap other views. - **`RenderBody()`**: called in the layout where the content view's output goes; normally exactly once, since each call writes the body again. - **`RenderSection` / `RenderSectionAsync`**: placeholders in the layout for named blocks a view may supply with `@section Name { ... }`. - **`_ViewStart.cshtml`**: code that runs before every full view, conventionally just `@{ Layout = "_Layout"; }`. ## The layout ```razor <!DOCTYPE html> <html lang="en"> <head> <title>@ViewData["Title"] - HomeFinder</title> <link rel="stylesheet" href="~/css/site.css" /> </head> <body> <main>@RenderBody()</main> <script src="~/js/site.js"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html> ``` The `mvc` project template generates the same shape: `@RenderBody()` in the main container and `@await RenderSectionAsync("Scripts", required: false)` after the site script. ## How a request renders 1. The action returns `View(model)`; the engine finds `Views/Listings/Map.cshtml`. 2. Because it is a **main page**, the engine collects every `_ViewStart.cshtml` from the root of the view's path down to its folder and runs them root-first, closest-last; the last assignment to `Layout` wins. 3. The view executes into a buffer. Its `@section Scripts` block is not written yet; it is registered under the name `Scripts`. 4. The engine locates the layout. A bare name such as `_Layout` is searched like a partial (the controller's folder, then `Views/Shared`); a path such as `/Views/Shared/_Layout.cshtml` is used as given. 5. The layout executes. `RenderBody()` writes the buffered view output; `RenderSectionAsync("Scripts", ...)` writes the registered block. 6. A layout can itself set `Layout`, so nested layouts render from the inside out. Because the view runs first, `ViewData["Title"]` set in the view is available to the layout's `<title>`. ## The rules MVC enforces | Situation | Result | |---|---| | Layout never calls `RenderBody()` or `IgnoreBody()`, and the view defines no sections | `InvalidOperationException`: RenderBody has not been called, "To ignore call IgnoreBody()" | | View defines `@section Scripts`, layout never renders it | `InvalidOperationException`: the following sections have been defined but have not been rendered | | Layout calls `RenderSection("Scripts")` (required by default) and the view has none | `InvalidOperationException`: the layout page cannot find the section | | Layout calls `RenderSection("Scripts", required: false)` and the view has none | nothing is written | Useful helpers in the layout: `IsSectionDefined("Scripts")` to render a fallback when a view supplies nothing, and `IgnoreSection("Scripts")` when a layout deliberately drops a section. Sections are visible only to the **immediate** layout; a partial or a view component cannot render them, and a partial cannot define one for the layout. ## _ViewStart versus _ViewImports | | `_ViewStart.cshtml` | `_ViewImports.cshtml` | |---|---|---| | What it holds | C# code that runs before each full view | directives: `@using`, `@model`, `@inherits`, `@inject`, `@addTagHelper`, `@removeTagHelper`, `@tagHelperPrefix` | | When it applies | at render time, main views only | at compile time, to every view in its folder and below | | Typical content | `Layout = "_Layout";` | `@using HomeFinder.Models`, `@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers` | | Hierarchy | all files run, root first | `@using` and `@addTagHelper` accumulate; the closest `@model` or `@inherits` wins | Both normally sit directly in `Views/`, not in `Views/Shared`. ## A worked example of the cascade The listings site keeps `Views/_ViewStart.cshtml` with `Layout = "_Layout"`, and adds `Views/Print/_ViewStart.cshtml` with `Layout = "_PrintLayout"`. For `Views/Print/Brochure.cshtml` the engine runs the root file first, then the `Print` one, so the brochure gets `_PrintLayout`. The view itself can still override with `Layout = null;` to render bare HTML, because the value from the `_ViewStart` files is copied to the view before the view runs. `_PrintLayout.cshtml` may in turn set `Layout = "_Layout"` to reuse the shared head while replacing the navigation, which is a nested layout; each layout in the chain renders its child through `RenderBody()`. ## Practical guidance - Keep `Layout` assignment in `_ViewStart`, not in each view; override it per folder (`Views/Admin/_ViewStart.cshtml`) or per view (`Layout = "_PrintLayout";` or `Layout = null;`). - Make shell sections optional unless every page truly must supply them; a required section breaks every new page that forgets it. - Put page scripts in a `Scripts` section so they load after the shared scripts they depend on.
- A new view defines @section Head but the layout has no RenderSection("Head"). What happens?Rendering fails with `InvalidOperationException` listing the sections that were defined but not rendered by the layout. Either add `@await RenderSectionAsync("Head", required: false)` to the layout or call `IgnoreSection("Head")` there if dropping it is intentional.
- Why does a partial view never get the site layout, even though _ViewStart sets one?The engine collects `_ViewStart` files only for main pages; partials are rendered with `isMainPage: false`, so no `_ViewStart` runs and `Layout` stays null. That is what lets a partial be dropped into any page or returned on its own for an AJAX fragment.
- _ViewStart.cshtml also runs before every partial view.
- _ViewImports.cshtml is the place to set Layout for all views.
- A section defined in a view but never rendered is silently ignored.
- RenderSection("Scripts") is optional unless required: true is passed.
- A partial can define @section Scripts and have the layout render it.