我在 MVC5 应用程序中使用 MVC5 进行身份管理。该代码正在运行,但是当用户尝试注册并且不使用相同的密码和确认密码时,我遇到了问题。我没有为此使用任何前端检查,因此将注册数据发送到服务器。在服务器上存在模型错误并且 ModelState.IsValid 返回 false:
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
这是我的控制器方法。当我检查 ModelState 的值时,我看到有一个错误:
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
// Create a local login before signing in the user
var user = new User(model.UserName);
var result = IdentityManager.Users.CreateLocalUser(user, model.Password);
if (result.Success)
{
IdentityManager.Authentication.SignIn(AuthenticationManager, user.Id, isPersistent: false);
return Redirect("~/home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
我的 HTML:
<form action="/Account/Register" class="form" method="post">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div id="input-fields">
<div>
<input class="big medium-margin"
name="UserName"
pattern=".{5,}" title="5 characters minimum"
placeholder="Username"
required size="25" type="text" value="" />
</div>
<div>
<input name="Password"
pattern=".{5,}" title="5 characters minimum"
placeholder="Password"
required size="25" type="password" />
</div>
<div>
<input name="ConfirmPassword"
pattern=".{5,}" title="5 characters minimum"
placeholder="Confirm Password"
required size="25" type="password" />
</div>
</div>
<button type="submit">Register</button>
<button type="button" onclick="location.href='/Account/Login'">Login</button>
</form>
错误是:
ModelState.Values[2].Errors[0].ErrorMessage = The password and confirmation password do not match.
我如何安排将此消息返回到我的表单以便用户可以看到它?
我认为它应该显示在:
<div class="validation-summary-errors"><ul><li style="display:none"></li>
</ul></div>
但这将如何发生?