ASP.Net MVC: access control error messages in the controller?

Is there any way to access verification error messages in the controller. I do not find them anywhere in ModelState.

+3
source share
3 answers

An iteration over ModelState is used for this purpose. Something like that:

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();
}
+6
source

I understand this is old, but I just stumbled upon it, looking for something else and leaving it here - maybe someone might find it useful:

var err = ModelState.Values.SelectMany(x => x.Errors).Select(e => e.ErrorMessage);

foreach(var y in err)
{
    // add each to your list of strings
}
+1
source

You can check the object in the controller using Validator

0
source

All Articles