Asp.net-Mvc

在 OnActionExecuting 事件中更改模型

  • May 3, 2012

我在 MVC 3 中使用動作過濾器。

我的問題是我是否可以在將模型傳遞給 OnActionExecuting 事件中的 ActionResult 之前製作模型?

我需要在那裡更改其中一個屬性值。

謝謝,

活動中還沒有模型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";
   }
}

引用自:https://stackoverflow.com/questions/10416951