MVC Razor Validation Errors showing on page load when no data has been posted

前端 未结 4 1482
暖寄归人
暖寄归人 2020-12-09 16:03

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 messa

4条回答
  •  心在旅途
    2020-12-09 16:49

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

提交回复
热议问题