Change the model in OnActionExecuting event

后端 未结 1 2010
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 20:12

I\'m using Action Filter in MVC 3.

My question is if I can crafting the model before it\'s passed to the ActionResult in OnActionExecuting event?

I need to c

相关标签:
1条回答
  • 2020-12-17 20:45

    There's no model yet in the OnActionExecuting event. The model is returned by the controller action. So you have a model inside the OnActionExecuted event. That's where you can change values. For example if we assume that your controller action returned a ViewResult and passed it some model here's how you could retrieve this model and modify some property:

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

    If you want to modify the value of some property of the view model that's passed as action argument then I would recommend doing this in a custom model binder. But it is also possible to achieve that in the OnActionExecuting event:

    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";
        }
    }
    
    0 讨论(0)
提交回复
热议问题