w3resource

Create Layout View


In the previous tutorial, we learnt about the layout views, it's uses and importance. In this tutorial, we will learn about how to create a layout view in an ASP.NET MVC project.

To create a new layout view in an MVC project using Visual Studio, right click on the directory where you intend to create the layout page, click add and then select New item. In our case, we will be creating the layout page in the share folder inside the views directory, thus: Right click shared folder -> select Add -> click on New item. From the pop up, search for layouts and select MVC 5 Layout page as seen in the snapshot below.

asp.net Create Layout View

After a successful creation of a layout page, the contents of your newly created layout may likely be some startup html tags, to get you up and running.

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

Now to fully customize the layout page we just created, we will add footer and header sections as shown in the code snippet below:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/css")
</head>
<body>
    <nav class="panel-footer">
        @RenderSection("header", true)
    </nav>
    <div>
        @RenderBody()
    </div>
    <footer class="panel-footer">
        @RenderSection("footer", true)
    </footer>
</body>
</html>

Now, to above layout is ready to be extended and used by other views. To make use of this layout in other views, we simply reference this view using the @Layout property as illustrated in the below code snippet.

@{
    ViewBag.Title = "Another Page";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";
}
@section header{
<div class="jumbotron">
    <h2>Another</h2>
</div>
}
<div class="row">
    <div class="col-md-4">
        <p>This is body.</p>
    </div>
</div>
@section footer{
    <p class="lead">
        This is footer section.
     </p>
}

From the above code snippet, you can observe the header and footer sections, which we have earlier declared in our layout page, and set it required to true. From the above example, we believe you have seen how a layout page can quickly be created and used in an MVC application.