asp.net-mvc-3action-filtermodelstate

Check ModelState in action filter


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


Solution

  • 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
    }