ASP.NET MVC中ModelState.AddModelError中关键参数的意义是什么? [英] What is the point of the key parameter in ModelState.AddModelError in ASP.NET MVC?

查看:93
本文介绍了ASP.NET MVC中ModelState.AddModelError中关键参数的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器中添加了验证检查,如果验证失败,该检查将修改ModelState.

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

例如:

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;
}

但是,我从不知道要为ModelState.AddModelError中的key参数传递值. (在示例中,我只是将其设置为我的UI显示名称.)

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.)

该参数的用途是什么?

推荐答案

ValidationMessage HTML Helper使用该密钥来知道要显示的确切错误消息.

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

示例:

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

ValidationMessage帮助器将在ModelState词典中显示具有键名称"的消息.

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

这篇关于ASP.NET MVC中ModelState.AddModelError中关键参数的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆