11. Layouts and Partial Views
A layout is a master page that holds the parts shared by every page, such as the navbar, footer and CSS links. Each view fills the layout through RenderBody(). A partial view is a small reusable piece of markup, like a card or a row. _ViewStart.cshtml sets the default layout for all views.
Key points
- _Layout.cshtml lives in Views/Shared.
- @RenderBody() marks where the page content goes.
- @section lets a page add scripts or styles into a named place in the layout.
- Partial views are inserted with the partial tag helper.
- _ViewImports.cshtml holds common @using lines and tag helper registration.
Example: A layout
<!DOCTYPE html>
<html>
<head>
<title>@ViewData["Title"] - MyApp</title>
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<nav> ... navigation links ... </nav>
<main>
@RenderBody()
</main>
<footer> ... </footer>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Show explanation
Every view is inserted where RenderBody appears, so the navbar and footer are written only once.
Example: A partial view
@model Student
<tr>
<td>@Model.Name</td>
<td>@Model.Age</td>
</tr>
@* Use it in another view: *@
@foreach (var s in Model)
{
<partial name="_StudentRow" model="s" />
}
Show explanation
The row markup is written once and reused wherever students are listed.