愛上MVC3~在(zai)控制器或Action上動態設(she)定模板頁(Layout)
很多(duo)境況下(xia),我們(men)(men)需(xu)要設置自己模(mo)塊(kuai)的layout,即它(ta)的布局(ju)頁(ye)面,在(zai)MVC2中叫它(ta)模(mo)板頁(ye)面,你可以在(zai)return view方(fang)(fang)(fang)法時設置它(ta),當(dang)然,這不(bu)是(shi)一種好方(fang)(fang)(fang)法,因為(wei)我不(bu)想每個(ge)action都去設置一次,因為(wei)我們(men)(men)的controller一般指一個(ge)模(mo)塊(kuai),而一個(ge)模(mo)塊(kuai)下(xia)的action,它(ta)們(men)(men)的layout基本是(shi)相(xiang)同的,所以,有沒(mei)有一種方(fang)(fang)(fang)法,在(zai)controller級別(bie)來實現這個(ge)呢,呵呵,當(dang)然有,那就(jiu)是(shi)attribute特(te)性,我們(men)(men)在(zai)MVC環境下(xia),有一個(ge)ActionFilterAttribute,這個(ge)想畢(bi)大家都聽說過(guo),它(ta)記錄(lu)了頁(ye)面在(zai)渲(xuan)染前與(yu)渲(xuan)染后(hou)的狀態,這個(ge)特(te)性(或者(zhe)叫它(ta)過(guo)濾器)的代碼如下(xia):
// 摘(zhai)要: // Represents the base class for filter attributes. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter { // 摘要: // Initializes a new instance of the System.Web.Mvc.ActionFilterAttribute class. protected ActionFilterAttribute(); // 摘要: // Called by the ASP.NET MVC framework after the action method executes. // // 參數: // filterContext: // The filter context. public virtual void OnActionExecuted(ActionExecutedContext filterContext); // // 摘(zhai)要: // Called by the ASP.NET MVC framework before the action method executes. // // 參數: // filterContext: // The filter context. public virtual void OnActionExecuting(ActionExecutingContext filterContext); // // 摘要: // Called by the ASP.NET MVC framework after the action result executes. // // 參數: // filterContext: // The filter context. public virtual void OnResultExecuted(ResultExecutedContext filterContext); // // 摘要: // Called by the ASP.NET MVC framework before the action result executes. // // 參數(shu): // filterContext: // The filter context. public virtual void OnResultExecuting(ResultExecutingContext filterContext); }
OnActionExecuted,OnActionExecuting,OnResultExecuted和OnResultExecuting它們記錄一個action從加載到頁面最終顯示在瀏覽器上的全過程,這個東西我們一般用在頁面權限驗證,layout頁面控制上,它們的執行次序是:
OnActionExecuting action執行前
OnActionExecuted action執行后
OnResultExecuting 頁面渲染前
顯示頁面的內容
OnResultExecuted 頁面渲染結果
如圖所示
我們通過ActionFilterAttribute的(de)特性(xing),寫個派(pai)生類(lei),然后(hou)去(qu)覆寫它(ta)的(de)OnActionExecuted方法(fa),將layout頁面(mian)修改(gai)(注意是(shi)修改(gai),因為在action執行之后(hou)layout已經是(shi)默認的(de)布局頁了)
代碼如下(xia):
/// <summary> /// 自定義(yi)模板頁面 /// </summary> public class LayoutAttribute : ActionFilterAttribute { private readonly string _masterName; public LayoutAttribute(string masterName) { _masterName = masterName; } /// <summary> /// 頁面渲染結束后執(zhi)行(xing) /// </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; } } }
最后把它應(ying)用到controller或(huo)者(zhe)action上,使用很簡單