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
  • 24,169
  • 25
  • 107
  • 177

6 Answers6

38

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

return View ("NameOfView",masterName:"viewName");
Pravin Pawar
  • 2,559
  • 3
  • 34
  • 40
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;
        }
Mustafa ASAN
  • 3,747
  • 2
  • 23
  • 34
8

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

@ {
    Layout = ViewData["Layout"];
}
Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141
  • 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
  • 2
    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,395
  • 1
  • 27
  • 47
4

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

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

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,569
  • 1
  • 16
  • 28