ASP.Net MVC 4 - Layout and Section in Razor

Razor has a feature called "layouts" that allow you to define a common site template, and then inherit its look and feel across all the views/pages on your web application.

Introduction


Suppose you are developing an ASP.NET web application and you want to maintain a consistent look and feel across all the pages within you web application. You then have two options, the first one is to design the head, body and footer sections on each page. In this approach you need to write more code on each page so ASP.NET 2.0 introduced "Master Pages" that helps enable this when using .aspx based pages or templates. It is your second option. Razor also supports this concept with a feature called "layouts" that allow you to define a common site template, and then inherit its look and feel across all the views/pages on your web application.

Create an MVC Application


I will create a MVC application using Visual Studio 2012. So let's see step-by-step how to create a MVC application.

Step 1: Go to "File" -> "New" -> "Project...".

Step 2: Choose "ASP.NET MVC 4 Web Application" from the list then give the application name "LayoutMvcApplication" and set the path in the location input where you want to create the application.

Step 3: Now choose the Project Template "Empty" and select "Razor" as the view engine from the dropdown list.

Create Layout for Application


A layout is used to provide a consistent look and feel of all pages of a web application so we create a layout for the web application. Let's see the procedure for that.

Step 1: Create a "Content" folder in the root directory of the web application.

Step 2: Create a Style Sheet "Site.css" under the content folder. That CSS file contains all CSS classes necessary for a consistent web application page design.

Step 3: Create a "Shared" folder under the "View" folder.

Step 4: Create a "_Layout.cshtml" file under the "Shared" folder. The file "_Layout.cshtml" represents the layout of each page in the application. Right-click on the Shared folder in Solution Explorer then go to "Add" item and click on "View".

MVC-1.jpg

Now the View has been created. Write the following code in the "_Layout.cshtnl" file.

 

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title>@ViewBag.Title - Code Express</title>  
  6.     <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />  
  7.     <link rel="stylesheet" href="@Url.Content("~/Content/Site.css")" />  
  8. </head>  
  9. <body>  
  10.     <header>  
  11.             <div class="content-wrapper">  
  12.                 <div class="float-left">  
  13.                     <p class="site-title">  
  14.                         @Html.ActionLink("Code Express""Index""Home")  
  15.                     </p>  
  16.                 </div>  
  17.                 <div class="float-right">  
  18.                     <nav>  
  19.                         <ul id="menu">  
  20.                             <li>@Html.ActionLink("Home""Index""Home")</li>  
  21.                             <li>@Html.ActionLink("About""About""Home")</li>  
  22.                         </ul>  
  23.                     </nav>  
  24.                 </div>  
  25.             </div>  
  26.         </header>  
  27.     <div id="body">  
  28.         @RenderSection("featured", required: false)  
  29.         <section class="content-wrapper main-content clear-fix">  
  30.                 @RenderBody()  
  31.             </section>  
  32.     </div>  
  33.     <footer>  
  34.             <div class="content-wrapper">  
  35.                 <div class="float-left">  
  36.                     <p>© @DateTime.Now.Year – Code Express</p>  
  37.                 </div>  
  38.             </div>  
  39.         </footer>  
  40. </body>  
  41. </html>  
In this layout we are using a HTML helper method and some other system defined methods so let's see these methods one by one.

Url.Content(): Content() method is a method of UrlHelper class. It converts a virtual (relative) path to an application absolute path. It has one parameter of string type that is a virtual path of the content. It returns an application's absolute path. If the specified content path (parameter of the method) does not start with the tilde (~) character then this method returns contentPath unchanged. Url.Content() ensures that all links work no matter if the site is in a virtual directory or in the web site root.

Html.ActionLink(): The easiest way to render an HTML link in is to use the HTML.ActionLink() helper. With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action. ActionLink() is an extension method of the HtmlHelper class. It returns an anchor element (an element) that contains the virtual path of the specified action. When you use an ActionLink() method then you need to pass three string parameter. The parameters are linkText (the inner text of the anchor element), actionName (the name of the action) and controllerName (the name of the controller).

RenderSection(): RenderSection() is a method of the WebPageBase class. Scott wrote at one point, The first parameter to the "RenderSection()" helper method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional and allows us to define whether the section we are rendering is required or not. If a section is "required", then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (that can make it easier to track down content errors). It returns the HTML content to render.

RenderBody(): In layout pages, renders the portion of a content page that is not within a named section. It returns the HTML content to render. RenderBody is required since it's what renders each view.

The _ViewStart File

The "_ViewStart" file in the Views folder contains the following content:

  1. @{  
  2.     Layout = "~/Views/Shared/_Layout.cshtml";  
  3. }  
This code is automatically added to all views displayed by the application. If you remove this file then you must add this line to all views. 

Create Controller in MVC Application


You need to create a controller that contains an action method to render the view on the user interface. I will create a HomeController controller with two action methods, one is Index and the other is About. Both action methods execute when the request type is GET and renders a view on the browser. So use the following procedure.

Step 1: Right-click on the Controllers folder under Solution Explorer then go to "Add" and click on "Controller".

Step 2: Give the name HomeController for the Controller name input and select "Empty MVC controller" from the Template dropdown list. After that click on "Add".

Now you need to write the following code in the "HomeController.cs" file:

 

  1. using System.Web.Mvc;  
  2. namespace LayoutMvcApplication.Controllers  
  3. {  
  4.     public class HomeController : Controller  
  5.     {  
  6.         public ActionResult Index()  
  7.         {  
  8.             return View();  
  9.         }  
  10.         public ActionResult Index()  
  11.         {  
  12.             return View();  
  13.         }  
  14.     }  
  15. }  

Create View in MVC Application

You need to create two views (Index and About) that inherit the "_Layout" view via the "_ViewStart" view so you need to use the following procedure.

Step 1: Right-click on the Index() action method under the "HomeController.cs" file then click on "Add View".

Step 2: Leave Add New screen unchanged and click on "Add"

Now you should write the following code in your web application index view:

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4. @section featured  
  5. {  
  6.     <section class="featured">  
  7.         <div class="content-wrapper">  
  8.             <hgroup class="title">  
  9.                 <h1>@ViewBag.Title.</h1>                 
  10.             </hgroup>  
  11.             <p>  
  12.                It is featured section. That is named section in Layout template that defined by RenderSection  
  13.             </p>  
  14.         </div>  
  15.     </section>     
  16. }  
  17. <p> It is body of Index view that renders in BodyRender.</p>  
You can follow the same steps for the About view and create it.

MVC-2.jpg

You can get the same design for the About view. You can download the source code from the attachment.

With this code I want to share one more thing, that it is my maiden fifty of articles on C# Corner.