Get error message if ModelState.IsValid fails?

Try this

if (ModelState.IsValid)
{
    //go on as normal
}
else
{
    var errors = ModelState.Select(x => x.Value.Errors)
                           .Where(y=>y.Count>0)
                           .ToList();
}

errors will be a list of all the errors.

If you want to display the errors to the user, all you have to do is return the model to the view and if you haven’t removed the Razor @Html.ValidationFor() expressions, it will show up.

if (ModelState.IsValid)
{
    //go on as normal
}
else
{
    return View(model);
}

The view will show any validation errors next to each field and/or in the ValidationSummary if it’s present.

Leave a Comment