20 July 2017

How do you render different layout in ASP.NET MVC

There are several ways to render different layout in ASP.NET MVC. I just give preference to the 2 ways below.


A. By defining the layout on the view. For example:

Placing the below code on top of Index.cshtml of AdminController

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

then placing the below code on top of Index.cshtml of EmployeeController

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


B. By identifying the controller and render the Layout per controller in a single _ViewStart file in the root directory of the Views folder. For example:

@{
 var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
  string layoutSelection = "";
 if (controller == "Admin") 
 {
     layoutSelection = "~/Views/Shared/_AdminLayout.cshtml";
 }
 else
 {
     layoutSelection = "~/Views/Shared/_EmployeeLayout.cshtml";
 }
 Layout = layoutSelection ;
}

No comments:

Post a Comment