ASP.NET Core Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

Layouts and Partial Views in ASP.NET Core MVC

Back to: ASP.NET Core Tutorial

Layouts and partial views help keep your ASP.NET Core MVC app modular, maintainable, and consistent by separating common UI components.


🗂️ Layouts: Master Pages for Consistent Design

A Layout is like a master page. It contains the shared HTML structure (e.g., header, footer, navigation) that you want across multiple views.

📁 Default Location:

Views/Shared/_Layout.cshtml

🧩 Example _Layout.cshtml:

html
 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewData["Title"] - My App</title>
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <partial name="_Header" />
    </header>

    <main role="main" class="container">
        @RenderBody()
    </main>

    <footer>
        <partial name="_Footer" />
    </footer>

    @RenderSection("Scripts", required: false)
</body>
</html>
 

✅ Key Layout Features:

Feature Purpose
@RenderBody() Required. Renders the main view content.
@RenderSection() Optional. For page-specific content.
@ViewData["Title"] Custom page title

🧩 Using Layout in Views

Set the layout in a view:

csharp
 
@{
    Layout = "_Layout";
    ViewData["Title"] = "Home Page";
}
 
csharp
 
@{
    Layout = "_Layout";
}
 

🧩 Partial Views: Reusable UI Components

Partial views help you reuse common UI pieces like:

  • Navigation bars

  • Modals

  • Forms

  • Lists

📁 Default Location:

Views/Shared/_YourPartialView.cshtml

✅ Example: _Header.cshtml

html
 
<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/About">About</a></li>
    </ul>
</nav>
 

🧩 Include a Partial View:

csharp
 
<partial name="_Header" />
 

Or if the view needs a model:

csharp
 
@model MyApp.Models.User

<partial name="_UserProfile" model="Model.User" />
 

🔄 Partial vs Layout vs View Components

Feature Use Case
Layout Overall page structure
Partial View Reusable static fragments (forms, menus)
View Component Reusable logic + UI (with controller-like logic)

🔧 Summary

  • Use Layouts to maintain a consistent look across pages.

  • Use Partial Views to break complex views into manageable parts.

  • Define layout in _ViewStart.cshtml to apply it automatically.

  • Use @RenderSection for flexible page-specific content injection.

Scroll to Top