5

Can I check ModelState.IsValid in my custom action filter in OnActionExecuting method?

Dariusz Woźniak
  • 9,640
  • 6
  • 60
  • 73
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153

1 Answers1

11

Yes. ModelState is part ViewData. So you can get it using:

filterContext.Controller.ViewData.ModelState

For example, if you wanted to inject some code after the action executes, but only if ModelState.IsValid == true, you can do:

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    if (!filterContext.Controller.ViewData.ModelState.IsValid) return;
    // do something
}
awrigley
  • 13,481
  • 10
  • 83
  • 129