2012-07-18 41 views

回答

2

在ASP.NET MVC中,這將是一個action filter。如果你想在全球範圍內完成,你可以將其註冊爲global action filter。這樣它將適用於所有控制器操作,因此您不需要單獨裝飾它們。

所以,你的過濾器,可以這樣定義:

public class GlobalViewBagInjectorActionFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     filterContext.Controller.ViewBag.Foo = "bar"; 
    } 
} 

,並在RegisterGlobalFilters方法在Global.asax註冊:

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new HandleErrorAttribute()); 
    filters.Add(new GlobalViewBagInjectorActionFilter()); 
} 

現在,所有的意見裏面,你可以使用ViewBag.Foo屬性。

但是在大多數情況下,Child Actions是比ViewBag更好的替代方案,因爲它們允許您傳遞強類型的視圖模型,而不是依賴於弱類型的ViewBag和一些魔法字符串。

+0

我看過孩子的行爲,但是讓我失望的是,我仍然需要在路由中爲它定義url。這對我沒有意義。 – Kugel 2012-07-18 10:04:39

相關問題