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 ;
}

2 comments:

  1. It was really a nice post and I was really impressed by reading this .NET Online Course Hyderabad

    ReplyDelete
  2. Nice! you are sharing such helpful and easy to understandable blog. i have no words for say i just say thanks because it is helpful for me.


    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery




    ReplyDelete