问题
I'm using MVC 5 and want to override the below View method in my MVC controller
protected internal virtual ViewResult View(string viewName, string masterName, object model)
I can have a number of different layout views so want to get the current layout name at runtime and pass it to the overriden view method. How do I get the layout name at runtime in the controller?
EDIT I don't think I need to create a custom view engine for what I need to do. I basically only want to set a ViewBag value across multiple methods and controllers and don't want to repeat myself. I have the viewName and model values at runtime, just don't have the layout name to pass as the masterName parameter
protected override ViewResult View(string viewName, string masterName, object model)
{
ViewBag.SomeValue = GetValue();
return base.View(viewName, masterName, model);
}
回答1:
What are you using to make the decision at runtime - Is there some identifier that will tell you which Master to use??? Maybe you can make a Switch?
Switch (loggedInUser.SomeSpecialValue)
{
Case: "value1":
return "_Layout1.cshtml";
}
How else were you planning to make the decision as to which Layout to show?
Edit: Okay extending the above idea - Maybe something like this can help you:
RouteConfig
routes.MapRoute(
name: "Default",
url: "{layout}/{controller}/{action}/{id}",
defaults: new { layout = "default", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
HomeController
protected override ViewResult View(string viewName, string masterName, object model)
{
var layout = RouteData.Values["layout"].ToString();
switch (layout)
{
case "default":
return base.View(viewName, "_layout", model);
case "test":
return base.View(viewName, "_layout2", model);
}
return base.View(viewName, masterName, model);
}
Views Create Layout views as required, and add them to the Shared folder and the switch statement.
Test URL's
http://localhost:64372/ -> Default Layout
http://localhost:64372/default/home/index
http://localhost:64372/test/ -> 2nd Layout
http://localhost:64372/test/home/index
Hope this maybe works for you??
来源:https://stackoverflow.com/questions/34398490/get-layout-name-in-controller-method