2015-08-27 82 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