不显示验证摘要消息第一次MVC

Amn*_*mna 3 asp.net-mvc asp.net-mvc-4 asp.net-identity

我正在使用MVC Identity For Login和MVC Validation For Required Fields,我不想第一次显示错误消息.只有在用户点击提交按钮时才会显示.但是由于页面每次都会发布到ActionResult,所以它也向我展示了验证.什么是不在页面加载时第一次显示消息的方法.我已经使用此代码来清除消息,但每次都清除它

在此输入图像描述

public ActionResult Login(LoginModel model)
{
if (!ModelState.IsValid)
{
       return View("Login");
}
foreach (var key in ModelState.Keys)
{
   ModelState[key].Errors.Clear();
}
}
//Model
 public class LoginModel
{

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

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
   }

  //HTML
  @using (Html.BeginForm())
    {
        @Html.ValidationSummary("")
        @Html.TextBoxFor(model => model.Email, new { maxlength = "45", placeholder = "User Email" })
        @Html.PasswordFor(model => model.Password, new { maxlength = "45", placeholder = "User Password" })
        <button type="submit" class="LoginBtn" id="loginButton"></button>
   }
Run Code Online (Sandbox Code Playgroud)

小智 6

您需要LoginModel model从GET方法中删除该参数.发生的事情是,一旦调用该方法,就会DefaultModelBinder初始化一个新实例LoginModel.因为您没有为属性提供任何值LoginModel,所以它们是null,因此会添加验证错误ModelState,然后在视图中显示.相反,你的方法需要

public ActionResult Login()
{
  LoginModel model = new LoginModel(); // initialize the model here
  return View(model);
}
Run Code Online (Sandbox Code Playgroud)