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

.net, asp.net-mvc, c#

Solution

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.

Problem

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?

Original source