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.
If you're looking to generate a single error message string that contains the ModelState
error messages you can use SelectMany
to flatten the errors into a single list:
if (!ModelState.IsValid)
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}