Layouts in ASP.NET MVC


Like Master Page in Asp.Net web applications, Layout in Asp.Net MVC used to maintain consistent look for entire applications. In MVC single view acts as layout template for all views to define common styles. The layout template defines all common markup including CSS, HTML,…..etc. The other views which are using layout template contains only the contents within the locations where layout view indicates.

Let’s create simple Asp.Net MVC applications to learn the layouts. Open Microsoft Visual Studio 2013 => select ASP.NET MVC 4 Web Application template and name it as MVCLayouts. Asp.Net MVC created simple layout template _Layout.cshtml for us in Views folder as shown below.

_Layout.cshtml:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width" />

    <title>@ViewBag.Title</title>

    @Styles.Render("~/Content/css")

    @Scripts.Render("~/bundles/modernizr")

</head>

<body>

    @RenderBody()

 

    @Scripts.Render("~/bundles/jquery")

    @RenderSection("scripts", required: false)

</body>

</html>

 

As shown above @RenderBody renders the body of the view, @RenderSection renders the various parts of the view like header, footer….etc. Now let’s use this view as layout in another view as shown below. While creating the view select Layout as shown below. Right click on Controller Action method and select Add View, it displays the window as shown below.

Select “Use a layout or master page” checkbox and click the button to browse layout. It displays layouts window as shown below.

Select _Layout.cshtml as layout, Index.cshtml view creates as shown below.

@{

    ViewBag.Title = "Index";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

 

<h2>Index</h2>

 

Provide the header, footer and body to render in layout as shown below.

@{

    ViewBag.Title = "Index";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

 

<h2>Index</h2>

 

@section Header {

    <h1>

        Home Page<h1>

}

@section Footer {

    Copyright @DateTime.Now.Year

}

<div class="main">

    This is the main content.

</div>

 

In this way we can use this layout template _Layout.cshtml for any number of views within the application to maintain consistent look.