2015-08-27 93 views
-1

無法正確顯示用戶名或密碼不正確的登錄錯誤消息。我有一個稱爲用戶的模型和一個帶有Action Method Validate的Controller,它驗證了用戶名和密碼。成功驗證後,我重定向到創建操作方法,如果沒有,我添加模型錯誤,我想在登錄屏幕上顯示「無效的用戶名或密碼」消息。驗證錯誤未顯示(MVC4和EF)

Model: 

public class User 
{ 
    public int ID { get; set; } 
    [Required] 
    [Display(Name="User Name")] 
    public string UserName { get; set; } 
    [Required] 
    [DataType(DataType.Password)] 
    public string Password { get; set; } 
    [Required] 
    [Display(Name="First Name")] 
    public string FirstName { get; set; } 
    [Required] 
    [Display(Name="Last Name")] 
    public string LastName { get; set; } 
    [Required] 
    [DataType(DataType.PhoneNumber)] 
    [MinLength(10)] 
    [MaxLength(10)] 
    [Display(Name="Mobile No")] 
    public string PhoneNum { get; set; } 
} 

    Controller: 

    [HttpGet] 
    public ActionResult Validate() 
    { 

     return View(); 

    } 

    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public ActionResult Validate(User user) 
    { 


     var u1 = db.Users.Where(p => p.UserName == user.UserName && p.Password == user.Password).FirstOrDefault(); 
     if (u1 != null) 
     { 
      return RedirectToAction("Create"); 
     } 
     else 
     { 

      ModelState.AddModelError("", "The user name or password provided is incorrect."); 
     } 
     return RedirectToAction("Validate"); 


    } 

    View: 

    @model HindiMovie.Models.User 

    @{ViewBag.Title = "Login";} 

    <h2>Login</h2> 

    @using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(false,"The user name or password provided is incorrect.") 

    <fieldset> 
    <legend>User</legend> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.UserName) 
    </div> 
    <div class="editor-field"> 
     @Html.TextBoxFor(model => model.UserName) 
     @Html.ValidationMessageFor(model => model.UserName) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Password) 
    </div> 
    <div class="editor-field"> 
     @Html.PasswordFor(model => model.Password) 
     @Html.ValidationMessageFor(model => model.Password) 
    </div> 





    <p> 
     <input type="submit" value="Validate" /> 
    </p> 
</fieldset> 
} 

<div> 
@Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
@Scripts.Render("~/bundles/jqueryval") 
} 

回答

2

重定向重置ModelState。您可能想重新顯示視圖:

public ActionResult Validate(User user) 
{ 
    var u1 = db.Users.Where(p => p.UserName == user.UserName && p.Password == user.Password).FirstOrDefault(); 
    if (u1 != null) 
    { 
     return RedirectToAction("Create"); 
    } 

    ModelState.AddModelError("", "The user name or password provided is incorrect."); 
    return View(); 
} 
+0

謝謝先生。 :) – Sid