如何通过属性过滤器设置在MVC剃刀布局? [英] How to set a Razor layout in MVC via an attribute filter?

查看:80
本文介绍了如何通过属性过滤器设置在MVC剃刀布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过设置code默认剃刀布局在任何一个基本控制器或属性。这是在文档,这是可能的提及,但我无法弄清楚它是如何做。

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 it's done.

我知道有母版参数来查看可用的方法,但我想通过控制器返回的所有意见已经将此值自动进行设置。

I know there's the masterPage parameter to the View method available, but I would like all views returned by a controller to have this value set automatically.

和不,我不能,因为我的意见是要在不同的地方(这是不是一个正常的MVC站点配置)。

And no, I can't use _ViewStart for this since my views are going to be in various places (this is not a normal MVC site configuration).

感谢

推荐答案

我觉得你可以只写一个像ActionFilter ...

I think you could just write an ActionFilter like...

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";
           }
       }
}

我刚写了这个code。通过我的裤子座位,没有编译器,它可能不会编译,但你可能得到的想法。我认为IResultFilter是你想要的正确的接口,它具有视图显示之前执行正确的方法。如果这是正确的,你应该能够修改MasterName因为这是关于动态呈现的视图。

I just wrote this code by the seat of my pants with no compiler so it probably won't compile but you probably get the idea. I think IResultFilter is the correct interface you want, it has methods that execute right before the view is rendered. If this is correct, you should be able to modify the MasterName for the view that is about to be rendered on the fly.

这将是控制器code用途。

This would be the controller code usage.

[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.
   }
}

这篇关于如何通过属性过滤器设置在MVC剃刀布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆