Skip to main content

How to get all model validation errors in ASP.NET MVC?

In ASP.NET MVC you can get a list of all validation errors for your model from the ModelState

if (!ModelState.IsValid)
{
var modelErrors = new List<string>();
foreach (var modelState in ModelState.Values)
{
foreach (var modelError in modelState.Errors)
{
modelErrors.Add(modelError.ErrorMessage);
}
}
// Here you have the list of error, you can show them on the view or generate a erro string and display it using javascript.
}

If you want to display it in razor then you can use @Html.ValidationSummary().

Hope it will help to find the actual error from the modal state.

Tarun Dudhatra

Tarun is a writer of http://www.codingsharp.com website. He is a software professional with hands on 10+ years of experience. Generally he writes an article about microsoft technology, Javascript, SQL Server and JQuery. Here he shares his notes, experiences, examples.