4

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

3 Answers 3

7

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();
}
Sign up to request clarification or add additional context in comments.

Comments

2

I realize this is old but I just stumbled into it looking for something else and will leave it here - perhaps someone could 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
}

Comments

0

You can validate an object in the controller using the Validator

1 Comment

I don't need to validate in the controller -- that's already being done by the MVC framework -- I just want to access the error messages generated by the framework's validation process in the controller rather than the view. I want to place the messages into the master view via TempData

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.