A Razor layout puts repeated HTML in one .cshtml file instead of copying it into every view. It can hold the document structure, stylesheet link, and header; each view supplies its own content at @RenderBody(). For controller views, the usual location is Views/Shared/_Layout.cshtml. section 22.4
Listing 7.8 The contents of the _Layout.cshtml file in the SportsStore/Views/Shared folder
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SportsStore</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
This minimal layout shows the essential arrangement: a complete HTML document with @RenderBody() where view-specific content belongs. section 7.1.6
Choose how the layout is applied:
- For one controller view, set Layout = "_Layout" in a @{ ... } block. The Razor engine looks for that name in Views/[controller] and Views/Shared; the value needs neither a path nor a file extension. section 22.4
- For a default, put @{ Layout = "_Layout"; } in Views/_ViewStart.cshtml. Views can then concentrate on their unique content rather than repeating the HTML shell. section 7.1.6
- Razor Pages use the same layout elements and expressions, typically placing the file in Pages/Shared and the default selection in Pages/_ViewStart.cshtml. A layout beside a page takes precedence over one in Shared; a page can opt out with Layout = null. section 23.5.1
A layout can be shared without being identical on every page. A view can set ViewBag.Title for a common title or header; provide a fallback where the layout cannot count on that property being set. A value assigned in the view takes precedence over the same view-bag property assigned by the action method. section 22.4.1
Use @section Header { ... } in a view and @RenderSection("Header") in its layout when unique content belongs somewhere other than the body. @RenderBody() still inserts content outside sections. Required sections must be supplied, and a view cannot define a section the layout does not render; @RenderSection("Header", false) makes that section optional. Use a partial view instead when the goal is to reuse a fragment within views. section 22.4.4 section 22.7
Put shared styling in one place
Add the Bootstrap stylesheet and a common header to Views/Shared/_Layout.cshtml, leaving @RenderBody() in the content area. Views using that layout gain the shared styling while retaining their own page markup. Restart ASP.NET Core and request http://localhost:5000 to observe the result. section 7.5.2
