Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster") {
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
else {
cLayout = "~/Views/Shared/_Layout.cshtml";
}
Layout = cLayout;
}
Procedure 2 : Set Layout by Returning from ActionResult
One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.
public ActionResult Index()
{
SampleModel model = new SampleModel();
//Any Logic
return View("Index", "_WebmasterLayout", model);
}
Procedure 3 : View - wise Layout (By defining Layout within each view on the top)
ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
Procedure 4 : Placing _ViewStart file in each of the directories
This is a very useful way to set different Layouts for each Controller in your ASP.NET MVC application. If we want to set default Layout for each directories than we can do this by putting _ViewStart file in each of the directories with the required Layout information as shown below:
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}