Layouts are great way of setting common design to multiple pages in the web application.

Layout files can be created using HTML/CSS/JavaScript etc. and contains common design to multiple pages in the application.

It contains sections in which views can pass their data. By default, the views are inserted in layout file where we write @RenderBody().

asp.net mvc layout

Layouts usually start with an underscore sign and are placed in the Shared folder under Views.

Here is a sample layout file:

~/Views/Shared/_MasterLayout.cshtml

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>@ViewBag.Title</title>
      <link href="~/Content/Site.css" rel="stylesheet" />
      <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
   </head>
<body>

<div id="main-container">
   <header>
     <div id="header"></div>
   </header>

   <section>
     <div id="content">
         @RenderBody() 
     </div>
   </section>
 
   <footer>
     <div id="footer">&copy; Content</div>
   </footer>
</div>
 
</body>
</html>

In the above file, @RenderBody is used to provide a place holder where we our views are inserted at runtime.

A basic view file can be like this:

~/Views/Static/Test.cshtml

@{
   Layout = "~/Views/Shared/_MasterLayout.cshtml";
}

This is view page

In the above view, we assume that we have a controller named StaticController and there is an action(method) named test() in it.

Passing view specific JavaScript and CSS to layout

We can create sections in our layout files to allow views to pass their specific data to the layout.

Let us check an example in which a view file passes page specific JavaScript and CSS to layout.

~/Views/Shared/_MasterLayout.cshtml

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>@ViewBag.Title</title>
      <link href="~/Content/Site.css" rel="stylesheet" />
      @RenderSection("CSS", false)
      <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
      @RenderSection("JavaScript", false)
   </head>
<body>

<div id="main-container">
   <header>
     <div id="header"></div>
   </header>

   <section>
     <div id="content">
         @RenderBody() 
     </div>
   </section>
 
   <footer>
     <div id="footer">&copy; Content</div>
   </footer>
</div>
 
</body>
</html>

We created two sections in this layout so that views can pass their page specific CSS and JavaScript files to the layout. Next we create the view file like this:

@{
    Layout = "~/Views/Shared/_MasterLayout.cshtml";
}
@section CSS
{
    <link href="~/Content/create-record.css" rel="stylesheet" />
}
@section Javascript
{
    <script src="~/Scripts/Custom/update-password.js"></script>
}

The above two sections will add the CSS and JavaScript files into the head section of the layout file.