What are different ways of rendering layout in ASP.NET MVC?

There are following four different ways of rendering layout in ASP.NET MVC:

  1. Using _ViewStart file in the root directory of the Views folder: The _ViewStart file with in Views folder is used to server the default Layout page for your ASP.NET MVC application. You can also change the default rendering of layouts with in _ViewStart file based on controller as shown below:
    @{
    	var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    	string layout = "";
    	if (controller == "Admin") {
    		layout = "~/Views/Shared/_AdminLayout.cshtml";
    	} else {
    		layout = "~/Views/Shared/_Layout.cshtml";
    	}
    	Layout = layout;
    }
  2. Adding _ViewStart file in each of the directories: You can also set the default layout for a particular directory by putting _ViewStart file in each of the directories with the required Layout information as shown below:
  3. Defining Layout with in each view on the top
    @{
        Layout = "~/Views/Shared/_AdminLayout.cshtml";
    }
  4. Returning Layout from ActionResult
    public ActionResult Index()
    {
        RegisterModel model = new RegisterModel();
        //TO DO:
        return View("Index", "_AdminLayout", model);
    }
Tagged , . Bookmark the permalink.

Leave a Reply