Valamas
Valamas

Reputation: 24759

How to set layout from controller

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

Answers (6)

Jonny C
Jonny C

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

Mustafa ASAN
Mustafa ASAN

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

James Simm
James Simm

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

Andrew
Andrew

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

Pravin Pawar
Pravin Pawar

Reputation: 2569

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

return View ("NameOfView",masterName:"viewName");

Upvotes: 39

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35689

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

@ {
    Layout = ViewData["Layout"];
}

Upvotes: 9

Related Questions