The Layout property controls which Razor layout wraps a view. A layout holds shared HTML, while @RenderBody() receives the view-specific content. Assign a layout name without a path or extension; Razor searches the controller and Shared view folders. section 22.4
Select a layout in a view
A view can select a shared layout directly: @{ Layout = "_Layout"; }. Its remaining markup is inserted into the layout's @RenderBody() position. A _ViewStart.cshtml file can set the same value once for a folder, avoiding repetition across views. section 22.4 section 22.4.2
Override the default when the view's rendering needs differ:
- Assign another layout name in the view; the view value overrides _ViewStart.cshtml. section 22.4.3
- Assign an expression, such as a product price condition, to choose between layouts programmatically. section 22.4.3
- Set Layout = null when the view already contains a complete HTML document; otherwise the result can contain nested document structure. section 22.4.3
- Use a controller-specific _ViewStart.cshtml to apply a different default across one controller's views. section 22.4.3
Listing 22.10 Using a layout in the Index.cshtml file in the Views/Home folder
@model Product?
@{
Layout = "_Layout";
}
<div class="m-2">
<table class="table table-sm table-striped table-bordered">
<tbody>
<tr><th>Name</th><td>@Model?.Name</td></tr>
<tr>
<th>Price</th>
<td>
@Model?.Price.ToString("c")
(@(((Model?.Price / ViewBag.AveragePrice)
* 100).ToString("F2"))% of average price)
</td>
</tr>
<tr><th>Category ID</th><td>@Model?.CategoryId</td></tr>
</tbody>
</table>
</div>
Shows a view that assigns a layout while retaining only product-specific markup. section 22.4
The property is also available to Razor Pages. A Pages _ViewStart.cshtml supplies a default, while an individual page can set Layout = null. Layout files placed beside Razor Pages take precedence over files in the Shared folder. section 23.5.1
