Can I check ModelState.IsValid
in my custom action filter in OnActionExecuting
method?
Asked
Active
Viewed 2,775 times
5

Dariusz Woźniak
- 9,640
- 6
- 60
- 73

Sergey Metlov
- 25,747
- 28
- 93
- 153
1 Answers
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
-
Wow, thanks... funny how missing a simple thing like ModelState being a part of ViewData can be so annoying. This also works from the View! – M Thelen Jul 25 '12 at 14:31
-
It will, ViewData is nothing if not for the View. – awrigley Jul 18 '14 at 21:20