The difference between Html.Validate and Html.ValidateFor

Why do we use .Validate and .Validatefor for verification?

I use this, but I do not receive any error messages in the user interface.

The code

 <div> @{Html.BeginForm();} @Html.TextBoxFor(x => x.LastName, new { id = "txtLastName" }) @{Html.Validate("LastName");} @{Html.ValidateFor(x=>x.LastName);} <input type="submit" id="btnSubmit" value="Submit" /> @{Html.EndForm();} </div> 
+4
source share
2 answers

This behavior is intentional. Both of these assistants simply register the corresponding parameters for verification on the client side, without actually displaying any message if the verification is not performed. However, this message may still display in ValidationSummary .

If you want to show a message specific to a field / parameter, you should use ValidationMessage or ValidationMessageFor instead:

 @Html.ValidationMessage("LastName") @Html.ValidationMessageFor(x=>x.LastName) 
+10
source

If there are situations where you actually do not want the validation message to be visually displayed for each field (i.e. using Html.ValidationMessage), but rather allow the summary to be the only source of validation error messages (i.e. using Html.ValidationSummary) , you still need to somehow “run” the validation for certain fields that you want. This can be achieved using the Html.Validate / Html.ValidateFor <> methods in your view. These assistants will not visualize anything, but simply register the specified field for verification on the client side.

See this post for an answer. How does validation work in ASP.NET MVC 2?

+1
source

Source: https://habr.com/ru/post/1497388/


All Articles