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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1122997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:44:40  来源:igfitidea点击:

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

c#.netasp.net-mvc

提问by Frank Krueger

I've added validation checks in my controller that modify the ModelStateif 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 keyparameter in ModelState.AddModelError. (In the example, I just set it to my UI display name.)

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

What is the parameter for and how should I use it?

参数是什么以及我应该如何使用它?

采纳答案by Frank Krueger

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

ValidationMessage HTML Helper 使用 Key 来了解要显示的确切错误消息。

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”的消息。

回答by OutstandingBill

The keyparameter 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.

key参数可用于将验证错误与表单字段相关联,从而控制消息在屏幕上的显示位置。它可以与 HtmlHelper 类型的输入和简单的 HTML 输入一起使用。

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

如果您使用@Html.TextBoxFor(或类似)和 a @Html.ValidationMessageFor,您可以从name正在验证的字段的 HTML中获取键的值(使用 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");

回答by mk Mughal

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”的模型中的字段绑定

回答by yeti_c

Sorry to Necropost. The above answers didn't have this detail that I thought was useful (it was what I was looking for!!)

抱歉 Necropost。上面的答案没有我认为有用的细节(这正是我要找的!!)

In order to create 'Model Wide' Validation errors - then you simply add string.Empty as your Key.

为了创建“模型范围”验证错误 - 然后您只需添加 string.Empty 作为您的密钥。

e.g.

例如

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

Thanks to : http://www.tutorialsteacher.com/mvc/htmlhelper-validationsummaryfor the tip.

感谢:http: //www.tutorialsteacher.com/mvc/htmlhelper-validationsummary的提示。