Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass (or access) a controller's ModelState to an ActionFilterAttribute?

I have a custom validation attribute derived from action filter attribute. Currently the attribute simply sets an ActionParameter value indicating if the item validated was good or not and then the action has to have logic to determine what to do with information.

 public class SpecialValidatorAttribute: ActionFilterAttribute
 {
     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
          // ... valdiation work done here ...
          filterContext.ActionParameters["SpecialIsValid"] = resultOfWork;

          base.OnActionExecuting(filterContext);
     }
 }

 [SpecialValidator]
 public ActionResult Index(FormCollection collection, bool SpecialIsValid)
 {
     if(!SpecialIsValid)
         // add a modelstate error here ...

     // ... more stuff
 }

I would like to perform a ModelState.AddModelError() while in the attribute's OnActionExecuting() method which would save me having the controller perform this logic.

I've tried adding a ModelState property to attribute but this data does not appear to be available to pass into the attribute.

Is there a way to gain access to the ModelState from within the attribute?

like image 614
Sailing Judo Avatar asked Feb 28 '23 14:02

Sailing Judo


1 Answers

Assuming your controller class derives from System.Web.Mvc.Controller (probably this is the case) you could try this:

((Controller)filterContext.Controller).ModelState.AddModelError("key", "value");
like image 98
Darin Dimitrov Avatar answered Apr 05 '23 23:04

Darin Dimitrov