MVC Razor Validation Errors displayed on page load when data was not sent

I messed around with data annotations. When I click on the link to go to the page, verification messages are displayed, but I would like the verification messages not to appear until the data has been published.

View:

@Html.TextBoxFor(m => m.EmailAddress, new { @placeholder = "Enter Email", @class = "form-control" }) @Html.ValidationSummary(true, "Registration Failed. Check your credentials") @Html.ValidationMessageFor(m => m.EmailAddress, "You must enter a valid Email Address.") 

Model:

 [Required(ErrorMessage = "Email is required")] [DataType(DataType.EmailAddress)] [EmailAddress] [Display(Name = "Email Address: ")] public string EmailAddress { get; set; } 

Controller:

 [HttpGet] public ActionResult AddUser() { return View(); } [HttpPost] public ActionResult AddUser(UserCreateViewModel user) { if (ModelState.IsValid) { var success = UserRepository.AddUser(user); if (success) { return View("Success"); } } return View("AddUser"); } 

As I said, my problem occurs when the page loads in the AddUser window. When I click the link to view the AddUser page, after it is loaded, verification messages are displayed, but at that moment the data was not published and the model is empty.

+7
c # asp.net-mvc razor data-annotations asp.net-mvc-validation
source share
4 answers

Define a validation style:

 .validation-summary-valid { display:none; } 

So by default it is hidden. The error will display it.

+9
source share

You can clear the state of the model after binding the user:

 ModelState.Clear(); 

This is because ModelBinder sets up the ModelState binding. In every action that binds a model and returns a view with the same model, you will have this problem.

 [HttpPost] public ActionResult AddUser(UserCreateViewModel user) { if (ModelState.IsValid) { var success = UserRepository.AddUser(user); if (success) { return View("Success"); } } ModelState.Clear(); // <------- return View("AddUser"); } 
+8
source share
 .field-validation-valid { display: none; } 

Whenever a validation is triggered when the page loads, this ".field-validation-valid" value is automatically added to the class attribute of the input element being triggered.

By adding CSS to render it not as the value of a particular class, you will no longer see a validation message when loading the start page.

Validation messages will usually be displayed after a particular input element has been touched.

0
source share

$('.field-validation-error').html("");

-one
source share

All Articles