Partials and Layouts

Intermediate 20 min read Lesson 6 of 8

Layouts

Layouts provide a consistent structure across pages.

Creating a Layout

// Pages/Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
    <title>@ViewData["Title"]</title>
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <nav>...</nav>
    
    <div class="container">
        @RenderBody()
    </div>
    
    <footer>...</footer>
    
    <script src="~/js/site.js"></script>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

Using a Layout

// Pages/Index.cshtml
@page
@{
    Layout = "_Layout";
}

<h1>Welcome</h1>

// Or use _ViewStart.cshtml
@{ Layout = "_Layout"; }

Partials

Partials are reusable components that can be included in multiple pages.

Creating a Partial

// Pages/Shared/_ProductCard.cshtml
@model Product

<div class="card">
    <h3>@Model.Name</h3>
    <p>Price: @Model.Price.ToString("C")</p>
    <a href="/Products/Details/@Model.Id">View</a>
</div>

Using a Partial

// Using with model
@await Html.PartialAsync("_ProductCard", product)

// Using without model
@await Html.PartialAsync("_Header")

// Using with ViewData
@await Html.PartialAsync("_ProductCard", product, new ViewDataDictionary(ViewData) {
    { "ShowPrice", true }
})

Partial with Tag Helper

<partial name="_ProductCard" model="product" />

Sections

Sections allow you to inject content into specific areas of the layout.

// In layout
<head>
    @await RenderSectionAsync("Head", required: false)
</head>

// In page
@section Head {
    <style>
        .custom { color: red; }
    </style>
}
Key Takeaway

Layouts and partials help you maintain a consistent UI and avoid code duplication.

Test Your Knowledge - Take Quiz