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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With