Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC: Access validation error messages in the controller?

Tags:

asp.net-mvc

Is there a way to access validation error messages in the controller. I'm not finding them anywhere in ModelState.

like image 896
Faust Avatar asked Jan 20 '23 11:01

Faust


1 Answers

Iterating over ModelState is used for this purpose. Something along these lines:

if (!ModelState.IsValid)
{
    StringBuilder result = new StringBuilder();

    foreach (var item in ModelState)
    {
        string key = item.Key;
        var errors = item.Value.Errors;

        foreach (var error in errors)
        {
            result.Append(key + " " + error.ErrorMessage);
        }
    }

    TempData["Errors"] = result.ToString();
}
like image 119
archil Avatar answered Jan 30 '23 19:01

archil