Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is ModelState AddModelError in MVC?

AddModelError(String, Exception) Adds the specified model error to the errors collection for the model-state dictionary that is associated with the specified key. AddModelError(String, String)

What is the point of checking ModelState?

The ModelState has two purposes: to store the value submitted to the server, and to store the validation errors associated with those values.

What is the purpose of ModelState IsValid property?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.

What is ModelState IsValid in asp net core?

Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field.


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.


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


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.


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"