How to Call Layout View at Run Time in MVC

This article explains what layout is and how to use it. We can learn how to call the layout at run time.

What is layout


Master Pages were introduce in ASP.NET 2.0. Master Pages help reduce the code in web pages. A Master Page provides the ability to maintain a consistent look and feel in the entire application. Layout is a replacement of Master Pages in MVC.

Create MVC application

The following is the procedure for creating a MVC application.

  1. Go to "File" → "New" → "Project".

    create new MVC4 application

  2. Choose "ASP.NET MVC 4 Web Application" and name it “mvcDemo”.

    new internet application

  3. Choose the project template “Internet Application”.

    After expanding the views folder we get another folder called Shared. In the Shared folder we have the following files.

    • _layout.cshtml
    • _loginPartial.cshtml
    • Error.cshtml

    Note: if you are using vb.net then the file extension will be .vbhtml. If we want to call a view in the entire project then we put it into the shared folder.

    By default some code is written in _layout.cshtml. Let's add another layout.

    controller

    We name it _layoutNew and click on "Add".

    view in MVC4

    I copied what was in _layout.cshtml by default and pasted it into _layoutNew.cshtml and made some changes. In the header section delete all elements and create a new div that contains the text “This is new layout” with some CSS attribute.
    1. <header>  
    2. <div class="content-wrapper" style="font-family:Verdana; font-size:24px; font-weight:bold;">This is new layout</div>  
    3. </header>  

Calling methods of layout in MVC

There are three methods to call the Layout in MVC.

  1. We can call it directly by writing this code in the view:

    → index.cshtml
    1. @{  
    2.       Layout = "~/Views/Shared/_Layout.cshtml";  
    3.  }  
    → _ViewStart.cshtml

  2. We can write the code above in _ViewStart.cshtml. If you have written it in _ViewStart.cshtml then this is applicable for all views. We can write _ViewStart in a particular view folder also. If we want to use a layout file different from what is specified in _ViewStart.cshtml then we can use the first method, that is to write the code in the view.
    1. @{  
    2.       Layout = "~/Views/Shared/_Layout.cshtml";  
    3.  }  
    → HomeController.cs

  3. This method is used when we want to call the Layout at run time.
    1. public ActionResult Index()  
    2. {  
    3. ViewBag.Message = "Your app description page.";  
    4.   
    5. return View("Index","_layoutNew");  
    6. }  

Method 1 & 2 Output

method output

Method 3 Output

new layout

Note: We can write some logic in _ViewStart.cshtml.

Up Next
    Ebook Download
    View all
    Learn
    View all