如何通过属性过滤器在MVC中设置Razor布局?

Bri*_*nga 7 asp.net-mvc razor

我想通过基本控制器或属性中的代码设置默认的Razor布局.文档中提到这是可能的,但我无法弄清楚它是如何完成的.

我知道View方法的masterPage参数可用,但我希望控制器返回的所有视图都自动设置该值.

不,我不能使用_ViewStart,因为我的视图将在不同的地方(这不是一个普通的MVC站点配置).

谢谢

Jab*_*Jab 15

我想你可以写一个像ActionFilter一样......

public class YourCustomLayoutAttribute : ActionFilterAttribute, IResultFilter
{
      public override void OnResultExecuting(ResultExecutingContext filterContext)
      {
           var viewResult = filterContext.Result as ViewResult;
           if(viewResult != null)
           {
              // switch the layout
              // I assume Razor will follow convention and take the "MasterName" property and change the layout based on that.
              viewResult.MasterName = "CustomLayout";
           }
       }
}
Run Code Online (Sandbox Code Playgroud)

我只是在我的裤子座位上编写了这个代码,没有编译器,所以它可能不会编译,但你可能会得到这个想法.我认为IResultFilter是您想要的正确接口,它具有在呈现视图之前执行的方法.如果这是正确的,您应该能够修改即将呈现的视图的MasterName.

这将是控制器代码使用.

[YourCustomLayout] // this should trigger your custom action result for all actions
public class MyController : Controller
{
   public ActionResult Index()
   {
      return View("Index", "MainLayout"); // even if you were to use the overload to set a master, the action result should override it as it executes later in the pipeline.
   }
}
Run Code Online (Sandbox Code Playgroud)