Skip to main content

How to find all ModelState errors of a submitted form in ASP.NET Core MVC and Razor Pages

The ModelState class in ASP.NET encapsulates the state of model binding to a property of an action-method argument or to the argument itself, and ModelState.IsValid check is commonly used by the .NET Developers to check whether a web user has submitted a form with all of the necessary details and if they haven't, then the "check" can be used to return some validation errors. 

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    _context.Movies.Add(Movie);
    await _context.SaveChangesAsync();

    return RedirectToPage("./Index");
}

When you have a big form, which you shouldn't have as it is not a great experience for the end users, and if you need to check the model state errors, below is a way to do exactly that. 

ModelState.Values
.SelectMany(x=>x.Errors
.Select(x=>x.ErrorMessage))
.ToList()

This will return all of the ModelState errors and you can then investigate the issue easily and take the necessary action. 




Comments