简体   繁体   English

ASP.NET MVC中ModelState.AddModelError中的关键参数有什么意义?

[英]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. 我在我的控制器中添加了验证检查,如果验证失败,则会修改ModelState

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 . 但是,我永远不知道在ModelState.AddModelError传递key参数的值。 (In the example, I just set it to my UI display name.) (在示例中,我只是将其设置为我的UI显示名称。)

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. ValidationMessage HTML Helper使用密钥来了解要显示的确切错误消息。

Example: 例:

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

the ValidationMessage helper will display the message that has the key "Name" in the ModelState dictionary. ValidationMessage帮助程序将显示ModelState字典中具有键“Name”的消息。

The key parameter can be used to associate the validation error with a form field, and thus control where the message appears on-screen. key参数可用于将验证错误与表单字段相关联,从而控制消息在屏幕上的显示位置。 It can be used with both HtmlHelper-type inputs and with simple HTML inputs. 它既可以与HtmlHelper类型的输入一起使用,也可以与简单的HTML输入一起使用。

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). 如果您使用了@Html.TextBoxFor (或类似)和@Html.ValidationMessageFor ,则可以从要验证的字段的HTML name中获取密钥的值(使用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"); 如果您刚刚使用了HTML <input> ,则可以使用@Html.ValidationMessage("AKeyIMadeUp")添加验证占位符,并在其中显示一条消息: ModelState.AddModelError("AKeyIMadeUp", "The value you entered is no good"); .

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失效时你可以设置错误消息绑定到该字段,如as。

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

then your error message will be bind with field in model named "OldPassword" 那么你的错误信息将与名为“OldPassword”的模型中的字段绑定

Sorry to Necropost. 对不起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. 为了创建“模型范围”验证错误 - 然后您只需添加string.Empty作为您的密钥。

eg 例如

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

Thanks to : http://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary for the tip. 感谢: http//www.tutorialsteacher.com/mvc/htmlhelper-validationsummary提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM