验证错误未显示(MVC4和EF)

时间:2015-08-27 15:17:24

标签: asp.net-mvc entity-framework asp.net-mvc-4 authentication

对于错误的用户名或密码,未显示无效登录错误消息。我有一个名为User的模型和一个带有Action Method Validate的Controller,它验证用户名和密码。成功验证后,我重定向到Create Action方法,如果没有,我添加模型错误,我想显示"无效的用户名或密码"登录屏幕上的消息。

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")
}

1 个答案:

答案 0 :(得分: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();
}