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

后端 未结 4 1686
孤城傲影
孤城傲影 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 , 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");.

提交回复
热议问题