asp.net-mvc – 如何通过属性过滤器在MVC中设置Razor布局?
发布时间:2020-05-28 15:35:34 所属栏目: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.
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET:如何从javascript访问转发器生成的元素?
- asp.net – 关键字不支持:’元数据’.使用MVC3的Entityt框
- asp.net – WCF:是否有一个属性要在OperationContract中生
- asp.net-mvc – 使用NHibernate和Autofac管理多个数据库
- asp.net-mvc – ASP.NET MVC中的Flat和Nested ViewModel类
- asp.net-mvc – ASP.NET MVC 4邮政编码验证
- 在ASP.net C#中伪造浏览器请求
- asp.net-mvc – ASP.NET MVC:在其中生成带有自定义html的动
- .net – RESTful WCF的裸最低配置
- asp.net-mvc – ASP .Net MVC中购物车的会话变量的替代方法
