26

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....

Valamas
  • 23,171
  • 24
  • 104
  • 174

6 Answers6

38

View method has overload to set its master layout something like this

return View ("NameOfView",masterName:"viewName");
Pravin Pawar
  • 2,519
  • 2
  • 33
  • 38
12

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;
        }
MstfAsan
  • 3,679
  • 2
  • 22
  • 34
7

Using your code, you could put this in your View:

@ {
    Layout = ViewData["Layout"];
}
Rob Stevenson-Leggett
  • 34,539
  • 21
  • 86
  • 139
  • 1
    He's already set the ViewData["Layout"] in his code, this is what he needs to add to the view to make it work but I see what you're saying. – Rob Stevenson-Leggett Jul 21 '16 at 08:14
  • 1
    Works perfectly for me, Dotnet Core MVC doesn't have the property of MasterName on the view so I couldn't set that. I tweaked this code to be slightly more robust. Layout = (ViewData["Layout"] as String) ?? "_Layout"; – Matt Mar 17 '17 at 14:18
6

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?

Community
  • 1
  • 1
Andrew
  • 5,345
  • 1
  • 25
  • 46
4

In the controller you can set a masterpage like this. I'm using MVC 5.2

return View("ViewName", "MasterPageName", model)
Jonny C
  • 571
  • 3
  • 8
-2

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";
}
James Simm
  • 1,561
  • 1
  • 18
  • 27