Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check ModelState in action filter

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

like image 700
Sergey Metlov Avatar asked Sep 14 '11 20:09

Sergey Metlov


People also ask

How do I know if my ModelState is valid?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.

How do I access ModelState?

The ModelState can be accessed in View using the ViewData object in ASP.Net MVC Razor.

Which property is used to determine an error in ModelState?

Errors property and the ModelState. IsValid property. They're used for the second function of ModelState : to store the errors found in the submitted values.


1 Answers

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
}
like image 146
awrigley Avatar answered Sep 20 '22 12:09

awrigley