I\'d like to set a default Razor layout via code in either a base controller or an attribute. It was mentioned in the Docs that this is possible, but I can\'t figure out how
The easiest way I can think of doing this is by having your controllers derive from a custom base class that overrides the View method:
public class MyControllerBase : Controller {
public override ViewResult View(string viewName, string masterName, object model) {
if(String.IsNullOrEmpty(masterName)) {
masterName = GetDefaultLayout();
}
base.View(viewName, masterName, model);
}
public virtual string GetDefaultLayout() {
return // your default layout here
}
}
In the code above you could explicitly set the masterName to some hardcoded value. Or your Controllers could override the method to provide a Controller-specific layout. Or you could read it from some attribute on the Controller, something similiar to:
masterName = GetType().GetCustomAttributes().
OfType().FirstOrDefault().DefaultLayoutPage;
Of course you'd have to create your MyCustomAttribute.