方法就是使用:ActionFilterAttribute
它的几个方法:OnActionExecuted,OnActionExecuting,OnResultExecuted和OnResultExecuting,它们记录一个action从加载到页面最终显示在浏览器的全过程,这个东西一般用在页面权限验证,LayOut页面控制上
这里面的几个方法执行顺序:OnActionExecuting action执行前
OnActionExecuted action执行后
OnResultExecuting 页面渲染后
OnResultExecuted 页面渲染结果
可以通过ActionFilterAttribute的特性,写个派生类,然后去覆盖OnActionExecuted
将layout页面修改(注意是修改,因为在action执行后layout已经是默认的布局页了)
/// <summary> /// 自定义模板页面 /// </summary> public class LayoutAttribute : ActionFilterAttribute { private readonly string _masterName; public LayoutAttribute(string masterName) { _masterName = masterName; } /// <summary> /// 页面渲染结束后执行 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); var result = filterContext.Result as ViewResult; if (result != null) { result.MasterName = _masterName; } } }
最后把它应用到controller或者action上,使用很简单
[Filters.Layout("_LayoutEd")] public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View(); } [Filters.Layout("_LayoutEd")] public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } }