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
:
✅ 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:
🧩 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
🧩 Include a Partial View:
Or if the view needs a model:
🔄 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.