2015-05-28 65 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