Tuesday, January 21, 2014

Different ways of rendering layouts(Master page) in Asp.Net MVC.


Method 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder

We can change the default rendering of layouts with in _ViewStart file by using the below code:
@{
 var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();

 string layout = "";
 if (controller == "User")
 {
 layout = "~/Views/Shared/_UserLayout.cshtml";
 }
 else
 {
 layout = "~/Views/Shared/_Layout.cshtml";
 }

 Layout = layout;
}


Method 2 : Return Layout from ActionResult
We can also override the default layout rendering by returning the layout from the ActionResult by using the below code:
public ActionResult Index()
{
 RegisterModel model = new RegisterModel();
 //TO DO:
 return View("Index", "_UserLayout", model);
}
Method 3 : Define Layout with in each view on the top
We can also override the default layout rendering by defining the layout on the view by using the below code:
@{
 Layout = "~/Views/Shared/_UserLayout.cshtml";
}
Method 4 : Adding _ViewStart file in each of the directories
We 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:
@{
 Layout = "~/Views/Shared/_UserLayout.cshtml";
}

 

No comments:

Post a Comment