What is the point of the key parameter in ModelState.AddModelError in ASP.NET MVC?

Viewed 25993

I've added validation checks in my controller that modify the ModelState if the validation fails.

For example:

private bool ValidateMoney(string raw, string name, decimal min, decimal max) {
    try {
        var dec = Convert.ToDecimal(raw);

        if (dec < min) {
            throw new ArgumentOutOfRangeException(name + " must be >= " + min);
        }
        else if (dec > max) {
            throw new ArgumentOutOfRangeException(name + " must be <= " + max);
        }
    }
    catch (Exception ex) {
        ModelState.AddModelError(name, ex.GetUserMessage());
    }
    return ModelState.IsValid;
}

However, I never know value to pass for the key parameter in ModelState.AddModelError. (In the example, I just set it to my UI display name.)

What is the parameter for and how should I use it?

4 Answers

The Key is used by the ValidationMessage HTML Helper to know the exact error message to display.

Example:

<%=Html.TextBox("Name") %> <br />
<%=Html.ValidationMessage("Name") %>

the ValidationMessage helper will display the message that has the key "Name" in the ModelState dictionary.

Sorry to Necropost. The above answers didn't have this detail that I thought was useful (it was what I was looking for!!)

In order to create 'Model Wide' Validation errors - then you simply add string.Empty as your Key.

e.g.

ModelState.AddModelError(string.Empty, "This is my Model Level Message");

Thanks to : http://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary for the tip.

Related