MVC Razor Validation Errors showing on page load w

2019-01-25 06:51发布

I'm messing around with data annotations. When I click on a link to go to a page, the validation messages are being displayed, but I would like to have the validation messages not show unless data has been posted.

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

Like I said, my problem occurs on page load of the AddUser view. When I click on the link to view the AddUser page, validation messages are showing after it loads, yet at this point no data has been posted and the model is empty.

5条回答
爷、活的狠高调
2楼-- · 2019-01-25 07:20

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

查看更多
成全新的幸福
3楼-- · 2019-01-25 07:25
.field-validation-valid {
  display: none;
}

Whenever the validation triggers on page load, this ".field-validation-valid" value is automatically added to the class attribute of the triggered input element.

By adding CSS to display none as that particular class's value, you'll no longer see the validation messages on initial page load.

The validation messages will still display normally after the particular input element has been touched.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-25 07:29

This happened to me when, model was not passed to view and same action was used for both get and post.

I applied @Renan Araujo's solution

查看更多
The star\"
5楼-- · 2019-01-25 07:32

Set the validation style to:

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

So by default it's hidden. An error will trigger it to display.

查看更多
冷血范
6楼-- · 2019-01-25 07:33

You can clear model state after binding user:

ModelState.Clear();

This happens because ModelBinder will set ModelState on 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");
}
查看更多
登录 后发表回答