我有一个 MVC 应用程序,它具有默认登录功能,当我登录时没有选中Remember me
复选框模型状态添加了一个错误说:
"The Remember me? field is required."
使用RememberMe
密钥,它在模型类中未标记为必需。对我来说,记住我是可选的。
因此,当我if(ModelState.IsValid)
在验证用户之前进行检查时,由于 RememberMe 错误,IsValid 属性为 false。
所以目前我正在使用 ModelState["RememberMe"].Errors.Clear();
Login Action 方法和检查来删除这个错误ModelState.IsValid
。
有没有更好的方法来避免这个错误被添加到ModelState
?
我正在使用 VS 2012 RC
控制器
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl) {
ModelState["RememberMe"].Errors.Clear();
if(ModelState.IsValid) {
if(Membership.ValidateUser(model.UserName, model.Password)) {
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if(Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) {
return Redirect(returnUrl);
}
else {
return RedirectToAction("Index", "Home");
}
}
else {
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
模型
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
看法
@{ Layout = "~/Views/Shared/_lightLayout.cshtml"; }
@model MvcFoodService.Models.LoginModel
<div class="accountHeader">
<h2>
Log In</h2>
<p>
Please enter your username and password. @Html.ActionLink("Register", "Register")
if you don't have an account.</p>
</div>
@using(Html.BeginForm()) {
@Html.DevExpress().Label(settings => {
settings.Name = "UserNameLabel";
settings.Text = "User Name";
settings.AssociatedControlName = "UserName";
}).GetHtml()
<div class="form-field">
@Html.EditorFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
@Html.DevExpress().Label(settings => {
settings.Name = "PasswordLabel";
settings.Text = "Password";
settings.AssociatedControlName = "Password";
}).GetHtml()
<div class="form-field">
@Html.EditorFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="form-field">
@Html.DevExpress().CheckBox(settings => {
settings.Name = "RememberMe";
settings.Text = "Remember me?";
}).GetHtml()
</div>
@Html.DevExpress().Button(settings => {
settings.Name = "Button";
settings.Text = "Log On";
settings.UseSubmitBehavior = true;
}).GetHtml()
}