ソースコードから理解する技術-UnderSourceCode

手を動かす(プログラムを組む)ことで技術を理解するブログ

ASP.NET MVC - My MVC Applicationを解析してみる (5)Register - ロジック層

引き続きRegister.aspxの解析ですが、今度はデータアクセスの前処理である
エラーチェックを見ていきます。

◆AccountController.cs


91: [AcceptVerbs(HttpVerbs.Post)]
92: public ActionResult Register(string userName, string email,
string password, string confirmPassword)
93: {
94:
95: ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
96:
97: if (ValidateRegistration(userName, email, password, confirmPassword))
98: {
中略。登録処理・・・。
111: }
112:
113: // If we got this far, something failed, redisplay form
114: return View();
115:}
97行目のValidateRegistration()で入力チェックをするための関数を呼び出し、
エラーがあれば登録処理を実行せずに 114行目のreturn View()で画面にレスポンスを返します。
エラーがない場合は、前回みた登録処理を実行します。

◆AccountController.cs


215: private bool ValidateRegistration(string userName, string email,
string password, string confirmPassword)
216: {
217: if (String.IsNullOrEmpty(userName))
218: {
219: ModelState.AddModelError("username", "You must specify a username.");
220: }
221: if (String.IsNullOrEmpty(email))
222: {
223: ModelState.AddModelError("email", "You must specify an email address.");
224: }
225: if (password == null || password.Length < MembershipService.MinPasswordLength)
226: {
227: ModelState.AddModelError("password",
228: String.Format(CultureInfo.CurrentCulture,
229: "You must specify a password of {0} or more characters.",
230: MembershipService.MinPasswordLength));
231: }
232: if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
233: {
234: ModelState.AddModelError("_FORM",
"The new password and confirmation password do not match.");
235: }
236: return ModelState.IsValid;
237: }
エラーチェックを実行する関数は、AccountController.cs内に実装されています。
引数で受け取った画面の入力値がエラーかどうかを判定し、エラーの場合は ModelState.AddModelError()で
エラーメッセージを設定しています。

このModelStateの型はModelStateDictionaryであり、エラーメッセージを格納するコレクションだと考えればよさそうです。
コレクションなのでキーと値をペアで追加し、キーにはエラー箇所を、値にはエラーメッセージを設定します。

今回のまとめ
1.Controller内で、エラーチェック、およびエラー時・正常時のシステムの動きを実装している。
  つまりロジック層をControllerに実装している。
2.エラーメッセージの表示には、ModelStateDictionaryクラスを使用する。
3.エラーチェック自体は、サーバー側で行われる。
  ASP.NETの検証コントロールのようにJavaScriptが自動的に生成されて
  クライアント側でエラーチェックを行っているわけではない。