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

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?


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.


The key parameter can be used to associate the validation error with a form field, and thus control where the message appears on-screen. It can be used with both HtmlHelper-type inputs and with simple HTML inputs.

If you've used @Html.TextBoxFor (or similar) and a @Html.ValidationMessageFor, you can get the key's value from the HTML name of the field being validated (use Inspect Element).

If you've just used an HTML <input>, you can add a validation placeholder using @Html.ValidationMessage("AKeyIMadeUp"), and get a message to appear in it like this: ModelState.AddModelError("AKeyIMadeUp", "The value you entered is no good");.


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.


Actually you can set any validation message while your form submission unsuccessful suppose you make a field in model

[Required]
    [DataType(DataType.Password)]
    [Display(Name = "Current password")]
    public string OldPassword { get; set; }

and while your modelState got invalid you can set error message bind with that field like as.

ModelState.AddModelError("OldPassword", "Current Password do not match ");

then your error message will be bind with field in model named "OldPassword"