Search code examples
asp.net-mvcasp.net-mvc-3model-view-controlleraction-filter

Change the model in OnActionExecuting event


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 change one of the properties value there.

Thank you,


Solution

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