views:

659

answers:

1

I enjoy writing validation functions 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;
}

But, I never know what to put for that stupid "key" argument to ModelState.AddModelError. (In the example, I just set it to my UI display name.)

What were the MVC developers thinking when they added it?

+7  A: 

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.

Marwan Aouida
More proof that ASP.NET MVC was developed with nothing more sophisticated than a blog in mind.
Frank Krueger
Validation is used in all sort of applications, not only blogs.
Marwan Aouida