11

我在 MVC 3 中使用动作过滤器。

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

我需要在那里更改其中一个属性值。

谢谢,

4

1 回答 1

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";
    }
}

如果您想修改作为操作参数传递的视图模型的某些属性的值,那么我建议您在自定义模型绑定器中执行此操作。但也有可能在以下情况下实现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";
    }
}
于 2012-05-03T07:26:42.677 回答