ASP.NET Web Pages - Nested Layouts

Nested layouts are useful for large websites where certain elements may change but the design follows a primary layout. For example, with this website the left sidebar changes when you click on different tutorials, however the rest of the design is intact; this is a nested layout.

Continue on from the previous layouts tutorial; please go back and go through it if you have not done so already.

  1. Open the website LayoutPages in WebMatrix
  2. In the Shared folder create a new file called _Food.cshtml.

Insert the following:

@{
  Layout="~/shared/_Layout.cshtml";
}

@section sidebar
{

<h2>Hot Food</h2>
<p>Curry</p>
<p>Rice</p>
<p>Pizza</p>

}

@RenderBody()

When you create a nested layout, the first thing you need to do is link the nested layout to the main layout, and then call the RenderBody(). This defines the page as a layout page. The section sidebar is an optional content block we will use to change the content of the sidebar.

  1. In the Default.cshtml page, remove the @section sidebar (if it exists), change the layout to the _Food.cshtml page and run the website.

The website should run with the following content in the left sidebar:

Hot Food

Curry

Rice

Pizza

Now we need to expand on this more.

  1. In the Shared folder, create another file and name it _Drinks.cshtml.

Copy the following:

@{
    Layout="~/shared/_Layout.cshtml";
}
 
@section sidebar
{

<h2>Drinks</h2>
<p>Coke</p>
<p>Sprite</p>
<p>Irn-Bru</p>

}

@RenderBody()
  1. In the root directory create a page named Drinks.cshtml and insert the following code:
@{
  Page.Title = "Drinks";
  Page.mDescription = "Drinks";
  Layout="~/shared/_Drinks.cshtml";  
}
<p>Fresh drinks</p>

Run the Drinks.cshtml and you should see the content in the left sidebar change, however the layout is intact. This is a nested layout.

This is a simple process: The two layouts you created, _Food and _Drinks, are linked to the main Layout page. We still have to call RenderBody() because that defines these pages as layout pages. We then simply defined our @section sidebar { } and specified the content. When you run the default.cshtml and drinks page, all the layouts and content is merged together.

Essentially, you can add another page and link it to the Drinks or Food layout and you should see the layout appear. As a result, in the future if you want to change the food or drink list, you only need to edit it in one file.

Summary

Nested layouts are a great way to manage large websites and offer great flexibility when it comes to optional content and design features. This tutorial was an introduction to nested layouts pages. It is highly recommend that you continue exploring the many features of nested layouts so you can use them effectively.