Change the model in the OnActionExecuting event

I am using Action Filter in MVC 3.

My question is, can I create a model before passing it to ActionResult in the OnActionExecuting event?

I need to change one of the property values ​​there.

Thanks,

+6
source share
1 answer

There is no model in the OnActionExecuting event OnActionExecuting . The model is returned by the action of the controller. So you have a model inside the OnActionExecuted event. This is where you can change the values. For example, if we assume that your controller action returned a ViewResult and passed it some model here, how could you get this model and change 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 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 change the value of some property of the view model that is passed as an action argument, I would recommend doing this in a custom mediator. But this is also possible to achieve 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"; } } 
+24
source

Source: https://habr.com/ru/post/914732/


All Articles