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.
Calling methods of layout in MVC
There are three methods to call the Layout in MVC.
We can call it directly by writing this code in the view:
index.cshtml

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

_ViewStart.cshtml
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.

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

HomeController.cs
This method is used when we want to call the Layout at run time.

public ActionResult Index()
{
ViewBag.Message = "Your app description page.";
return View("Index","_layoutNew");
}

Method 1 & 2 Output

method output

Method 3 Output

new layout

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

I hope this article is helpful for you.

Thanks :)

Tags: , ,