I have an ASP MVC application which needs multiple different layouts. In ASP.NET Web Apps I would have just made separate master pages. How do I do this in ASP MVC 3?
So far I have made a separate Layout.cshtml file for each layout I need.
I tried setting the layout in the view but it is getting blown away from the ViewStart.cshtml which is setting it back to the default layout for the site.
Also, I can't seem to get intellisense working with Razor so I haven't been able to explore much of what I can do in the ViewStart, if I can conditionally set the Layout, or what.
Thoughts?
You could set the layout dynamically in your controller action:
public ActionResult Index()
{
var viewModel = ...
return View("Index", "_SomeSpecialLayout", viewModel);
}
You can manually set the layout for a view by writing @{ Layout = "~/.../Something.cshtml"; }
on top.
EDIT: You can pass the layout name as a parameter to the View()
method in the controller.
This method is the simplest way for beginners to control layout rendering in your ASP.NET MVC application. We can identify the controller and render the layouts as per controller. To do this we write our code in the _ViewStart
file in the root directory of the Views folder. The following is an example of how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "~/Views/Shared/_Layout.cshtml";
if (controller == "Webmaster") {
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
Layout = cLayout;
}
Read complete article I wrote here - "How to Render different Layout in ASP.NET MVC".