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

I have a special validation attribute derived from an action filter attribute. For the time being, the attribute simply sets an ActionParameter value indicating whether the checked item was good or not, and then the action should have logic to determine what to do with the 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 execute ModelState.AddModelError (), while in the OnActionExecuting () method, which will save me if the controller executes this logic.

I tried to add the ModelState property for the attribute, but this data does not seem to be available to go into the attribute.

Is there a way to access ModelState from an attribute?

+4
source share
1 answer

Assuming your controller class is derived from System.Web.Mvc.Controller (maybe this is the case), you could try the following:

 ((Controller)filterContext.Controller).ModelState.AddModelError("key", "value"); 
+8
source

All Articles