Course contentsShow
← C#
Lesson 1300 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Layout Templates and Nested Views

Construct modular page architectures using layout files and RenderBody sections.

In this lesson, you will learn how to create a consistent, modular UI architecture by using Razor Layouts to host dynamic page content.

The Problem: UI Redundancy

Imagine building a website with twenty pages. Each page needs the same navigation bar, footer, and sidebar. Without a template, you would be forced to copy-paste the same HTML into every file. If you wanted to change the logo, you’d have to update twenty files. Layout templates solve this by defining a "shell" that stays static while the unique content of your page is injected inside.

Using Layouts and RenderBody

A layout file (typically _Layout.cshtml) acts as a wrapper. Within this file, you use the @RenderBody() directive to specify exactly where the content of your specific view should be placed when a user visits a page.

Here is a simplified example of how your layout defines the structure:

<!-- Views/Shared/_Layout.cshtml -->
<html>
    <body>
        <nav>My Website Navigation</nav>
        
        <main>
            @RenderBody() <!-- The content of your page is injected here -->
        </main>

        <footer>© 2023 My C# Course</footer>
    </body>
</html>

Nested Views

When you create a specific page (e.g., Home.cshtml), you don't need the <html> or <body> tags. You simply point to the layout file at the top of your view. If you want to use a specific layout, you define it like this:

@{
    Layout = "_Layout.cshtml";
}

<h1>Welcome to my Homepage</h1>
<p>This content will be injected into the main tag of the layout.</p>

By separating the "container" from the "content," you ensure that your site structure is managed in one central location. If you need to add a new link to the navigation, you update the _Layout.cshtml file once, and every page in your application reflects that change instantly. This approach minimizes maintenance and keeps your codebase clean and professional.

Key Takeaway: Layout templates allow you to define a reusable UI shell, while @RenderBody() serves as the dynamic placeholder that injects individual page content into that structure.