我想通过基本控制器或属性中的代码设置默认的 Razor 布局。文档中提到这是可能的,但我不知道它是如何完成的。
我知道 View 方法有 masterPage 参数可用,但我希望控制器返回的所有视图都自动设置此值。
不,我不能为此使用 _ViewStart,因为我的视图将位于不同的位置(这不是正常的 MVC 站点配置)。
Thanks
我认为你可以写一个 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.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)