简体   繁体   中英

Modify a model in an ActionFilter

I have an actionfilter that I am running OnActionExecuting in ASP.NET MVC 2. Essentially I would like the actionfilter to sanitize my data and replace the current model (which will be passed to subsequent action filters and also my action method) with the sanitized model. Is this possible and is it a bad idea - if so why?

Thank you in advance, JP

If you need to deal with your models, you're likely going to be dealing more within the scope of a single Controller (unless all your Controllers use the same model types?). An alternate approach would be to override the OnActionExecuting() and OnActionExecuted() methods of the Controllers themselves. This allows you to keep your business logic within the controller scope.

Generally ActionFilters are used for cross-cutting concerns - something that you want to run for many action methods, regardless of where they exist in the app. So unless your model sanitization logic applies across many controllers and actions, or is very generic (which perhaps it is, in which case your approach is probably good), you might want to bring it out of the filters and into your controllers. If it's something that can apply broadly, then an ActionFilter is just fine.

Here's for MVC v1, I hope this is not changed in v2:

var view = filterContext.Result as ViewResultBase;
if (view != null)
   view.ViewData.Model ...

I don't see why you want to do it in OnActionExecuting, but if you must , do it there, and set some flag (private field) that OnActionExecuted has to tweak the resulting Model. But you'll have to use the latter anyway, except if you assign the .Result - in this case your action won't be called at all and the assigned result will be used.

BTW,对于MVC 3和4:

filterContext.Controller.ViewData.Model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM