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

后端 未结 4 1559
孤城傲影
孤城傲影 2021-02-06 20:29

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

For example:



        
相关标签:
4条回答
  • 2021-02-06 21:20

    The key parameter 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.

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

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

    0 讨论(0)
  • 2021-02-06 21:21

    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.AddModelError("OldPassword", "Current Password do not match ");
    

    then your error message will be bind with field in model named "OldPassword"

    0 讨论(0)
  • 2021-02-06 21:25

    Sorry to 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.

    e.g.

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

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

    0 讨论(0)
  • 2021-02-06 21:33

    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.

    0 讨论(0)
提交回复
热议问题