6

模型在MVC我使用行爲過濾3.更改OnActionExecuting事件

我的問題是,如果之前它傳遞給OnActionExecuting事件的ActionResult我各具特色的模式?

我需要更改其中的一個屬性值。

謝謝

+0

您能否解釋爲什麼您需要這樣做?我懷疑有更好的方法來完成你所需要的。 – DMulligan

+0

其中一個模型屬性決定視圖的外觀如下:編輯器或顯示器,我想根據用戶權限對其進行設置 –

+0

爲什麼要保留類似於模型屬性的東西?相反,你應該檢查視圖內的用戶權限並決定渲染哪個模板(編輯器或顯示) –

回答

24

有在OnActionExecuting事件沒有模型呢。該模型由控制器操作返回。所以你在OnActionExecuted事件中有一個模型。這就是你可以改變價值的地方。例如,如果我們假設你的控制器操作返回的ViewResult,並通過在這裏的一些模式就是你如何能找回這種模式並修改一些屬性:如果要修改視圖模型的某些屬性的值

public class MyActionFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     var result = filterContext.Result as ViewResultBase; 
     if (result == null) 
     { 
      // The controller action didn't return a view result 
      // => no need to continue any further 
      return; 
     } 

     var model = result.Model as MyViewModel; 
     if (model == null) 
     { 
      // there's no model or the model was not of the expected type 
      // => no need to continue any further 
      return; 
     } 

     // modify some property value 
     model.Foo = "bar"; 
    } 
} 

這是通過作爲動作參數,然後我會建議在自定義模型聯編程序中執行此操作。但是也可以在OnActionExecuting事件中實現:

public class MyActionFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     var model = filterContext.ActionParameters["model"] as MyViewModel; 
     if (model == null) 
     { 
      // The action didn't have an argument called "model" or this argument 
      // wasn't of the expected type => no need to continue any further 
      return; 
     } 

     // modify some property value 
     model.Foo = "bar"; 
    } 
} 
+1

謝謝,真的很有用! –

+0

嗨,你可能知道我怎麼能得到動作的傳遞參數,如OnActionExecuting事件中的ActionDescriptor.ActionParameters? –

+0

這就是我在我的回答中展示的內容:'filterContext.ActionParameters [「parameterName」]'。 –