MVC5 アプリケーションで ID 管理に 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>
しかし、これはどのように起こるのでしょうか?