Check ModelState in Filter Action

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

+4
source share
1 answer

Yes. ModelState is part of ViewData. Therefore, you can get it using:

 filterContext.Controller.ViewData.ModelState 

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

 public override void OnActionExecuted(ActionExecutedContext filterContext) { if (!filterContext.Controller.ViewData.ModelState.IsValid) return; // do something } 
+9
source

All Articles