加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何通过属性过滤器在MVC中设置Razor布局?

发布时间:2020-12-16 04:18:14 所属栏目:asp.Net 来源:网络整理
导读:我想通过基本控制器或属性中的代码设置默认的Razor布局.文档中提到这是可能的,但我无法弄清楚它是如何完成的. 我知道View方法的masterPage参数可用,但我希望控制器返回的所有视图都自动设置该值. 不,我不能使用_ViewStart,因为我的视图将在不同的地方(这不是
我想通过基本控制器或属性中的代码设置默认的Razor布局.文档中提到这是可能的,但我无法弄清楚它是如何完成的.

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

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

谢谢

解决方法

我想你可以写一个像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";
           }
       }
}

我只是在我的裤子座位上编写了这个代码而没有编译器所以它可能不会编译但你可能会得到这个想法.我认为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.
   }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读