Create a Layout View

You learned what is the layout view in ASP.NET MVC. Here you will learn how to create a layout view using Visual Studio.

You can create a layout view in any folder under the Views folder. However, it is recommended to create all the layout views in the Shared folder for easy maintenance purpose.

To create a new layout view in Visual Studio, right-click on the Shared folder -> select Add -> click on New Item... This will open the Add New Item popup, as shown below.

Create Layout View

In the Add New Item dialogue box, select MVC 5 Layout Page (Razor) template, and specify a layout view name as _myLayoutPage.cshtml and click Add to create it as shown below. Prefixing the underscore _ before layout view name is a common naming convention in ASP.NET MVC.

_myLayoutPage.cshtml
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now, let's add the common <footer> tag with the RenderSection("footer",true) method, as shown below. Please notice that we made this section as required. It means any view that uses the _myLayoutPage as its layout view must include a footer section.

Example: Adding RenderSection
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div>
        @RenderBody()
    </div>
    <footer class="panel-footer">
        @RenderSection("footer", true)
    </footer>
</body>
</html>

Now, create a new child view and select _myLayoutPage.cshtml as a layout view, as shown below.

This will create a new Index.cshtml as shown below.

Index.cshtml
@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_myLayoutPage.cshtml";
}

<h2>Index</h2>

Now, add the footer section because _myLayoutPage.cshtml contains the mandatory footer section, as shown below.

Index.cshtml
@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_myLayoutPage.cshtml";
}

<h2>Index</h2>
<div class="row">
    <div class="col-md-4">
        <p>This is body.</p>
    </div>
    @section footer{
        <p class="lead">
            This is footer section.
        </p>
    }
</div>

Now, run the application, and you will see that the Index view will be displayed in the RenderBody() method, and the footer section will be displayed in the RenderSection("footer", true), as shown below.

Thus, you can create a new layout view with a body and different sections.