Get error message if ModelState.IsValid fails?
If Modal State is not Valid & the error cannot be seen on screen because your control is in collapsed accordion, then you can return the HttpStatusCode so that the actual error message is shown if you do F12. Also you can log this error to ELMAH error log. Below is the code
if (!ModelState.IsValid)
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
//Log This exception to ELMAH:
Exception exception = new Exception(message.ToString());
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
//Return Status Code:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}
But please note that this code will log all validation errors. So this should be used only when such situation arises where you cannot see the errors on screen.
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.
You can do this in your view without doing anything special in your action by using Html.ValidationSummary() to show all error messages, or Html.ValidationMessageFor() to show a message for a specific property of the model.
If you still need to see the errors from within your action or controller, see the ModelState.Errors property
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);
}