views:

119

answers:

2

Hello, 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

+1  A: 

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.

womp
I definitely see your point but the sanitization is very much a CCC and will be used across controllers and action methods.
JP
+1  A: 

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.

queen3
I am attempting to access the model OnActionExecuting (i.e. before the action executes) so in this case the Model will always return null....
JP
I should have been more explicit - the reason i want to (must) do it OnActionExecuting is so tht i can still fire the ValidateInput filter (and don't have to turn it off!!!). If my properties contain HTML at that point they will be flagged as dangerous and the filter will fail (for want of a better term). The data needs to be updated prior to hitting this second filter, therefore OnActionExecuted is too late...
JP