Reputation: 24759
Is there a way to set the layout from the controller?
have tried:
ViewData["Layout"] = "..."
return View("view", Model);
I know it will sound odd with some people....
Upvotes: 27
Views: 23844
Reputation: 601
In the controller you can set a masterpage like this. I'm using MVC 5.2
return View("ViewName", "MasterPageName", model)
Upvotes: 5
Reputation: 3835
In action method you can use MasterName property in ViewResult class to change layout page.
public ActionResult Index()
{
var myView = View();
myView.MasterName = "~/Views/Shared/_Layout2.cshtml";
return myView;
}
Upvotes: 12
Reputation: 1579
If you have a _ViewStart.cshtml file in your Views directory, you can automatically set the layout for all views within the same folder (and sub-folders):
@{
Layout = "~/Views/Shared/Layout.cshtml";
}
Upvotes: -3
Reputation: 5430
Daren Dimitrov has a very nice answer on this one with Attributes:
How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?
Upvotes: 7
Reputation: 2569
View method has overload to set its master layout something like this
return View ("NameOfView",masterName:"viewName");
Upvotes: 39
Reputation: 35689
Using your code, you could put this in your View:
@ {
Layout = ViewData["Layout"];
}
Upvotes: 9