How to set a Razor layout in MVC via an attribute filter?

前端 未结 2 1188
既然无缘
既然无缘 2020-12-31 21:03

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

2条回答
  •  心在旅途
    2020-12-31 21:44

    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.

提交回复
热议问题