I\'m using ASP.NET MVC 3 with Razor views. When you want to create a view you can choose a layout (master page) for your view, or leave it to choose Default (_Layout).
I
There are multiple ways to specify a different layout for a view, depending on your needs:
As mentioned in other answers, simply change the view's Layout
property:
@{
Layout = "~/Views/Shared/_CustomLayout.cshtml";
}
MVC 3 added a default Views/_ViewStart.cshtml
into which you can put logic which is shared by all views. You can also create additional _ViewStart.cshtml
files in any Views subdirectory for additional custom logic (it will search up the hierarchy and in Shared
folders, just like when finding any other view or partial).
Putting a lot of business logic into this feels like a violation of the "separation of concerns" principle, but at the same time it can be very handy.
Note that _ViewStart.cshtml
inherits from StartPage, not WebPage, so its properties may be slightly different from what you're used to (e.g. you have to go through ViewContext
to get the ViewBag
).
@{
if (ViewContext.ViewBag.IsAdmin) // or other custom logic
{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
The View()
method has an overload which takes an explicit layout page (Intellisense refers to it as a "master page"):
public ActionResult FooAction()
{
var model = new MyModel();
return View("Index", "_CustomLayout", model);
}