在OnActionExecuting事件中更改模型

Yai*_*vet 9 model-view-controller asp.net-mvc action-filter asp.net-mvc-3

我在MVC 3中使用Action Filter.

我的问题是,我是否可以在将模型传递给OnActionExecuting事件中的ActionResult之前制作模型?

我需要更改其中一个属性值.

谢谢,

Dar*_*rov 26

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要修改作为操作参数传递的视图模型的某些属性的值,那么我建议在自定义模型绑定器中执行此操作.但在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";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您无法访问`OnActionExecuted`方法中的操作参数.那是因为这个方法执行时不再有动作了.行动已经结束.从`filterContext.ActionDescriptor`属性,您可以获得列表和每个参数的类型,但不能获取值.一种可能性是在`OnActionExecuting`方法中存储HttpContext中需要访问的值,然后在HttpContext的`OnActionExecuted`方法中检索它们. (2认同)