2015-05-28 62 views
1

我正在使用MVC身份登录和MVC验证对于必填字段,我不想第一次显示错误消息。只有当用户点击提交按钮时才会显示。但是随着页面每次都发布到ActionResult,所以它也向我展示了验证。 什么是在页面加载时不首次显示消息的方法。 我已经使用这个代码清除的消息,但明确每次都不显示验证摘要消息第一次MVC

enter image description here

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> 
    } 
+1

保持这种风格在页面'.validation-汇总有效{显示:无; }' –

+0

显示你的GET方法 - 你似乎有一个模型参数(这是错误的) –

+0

我已经添加完整的代码斯蒂芬 – Diana

回答

5

您需要从GET方法去除LoginModel model参数。发生什么情况是DefaultModelBinder在调用方法后立即初始化LoginModel的新实例。因为您没有为LoginModel的属性提供任何值,所以它们是null,因此将验证错误添加到ModelState,然后将其显示在视图中。相反,你的方法必须是

public ActionResult Login() 
{ 
    LoginModel model = new LoginModel(); // initialize the model here 
    return View(model); 
} 
+0

是的它的工作原理。我使用操作筛选器[HttpGet]和[HttpPost]分隔了Get和Post Action。谢谢斯蒂芬。 – Diana

+0

我在同一天给了你的投稿1亲爱的。 – Diana