Asp.net-mvc-model-binding

提供:Dev Guides
移動先:案内検索

ASP.NET MVC-モデルバインディング

ASP.NET MVCモデルバインディングを使用すると、HTTP要求データをモデルにマップできます。 これは、ブラウザがHTTPリクエストで送信したデータを使用して.NETオブジェクトを作成するプロセスです。 ASP.Net MVCを初めて使用するASP.NET Webフォーム開発者は、Viewの値がControllerクラスのActionメソッドに到達したときにModelクラスに変換される方法がほとんど混乱しているため、この変換はModelバインダーによって行われます。

モデルバインディングは、HTTPリクエストとC#アクションメソッド間の適切に設計されたブリッジです。 POSTとGETは指定したデータモデルに自動的に転送されるため、開発者はフォーム(ビュー)のデータを簡単に操作できます。 ASP.NET MVCはデフォルトのバインダーを使用して、これを舞台裏で完了します。

前の章のプロジェクトに「ビューの作成」を追加する簡単な例を見てみましょう。これらの値をビューからEmployeeControllerアクションメソッドに取得する方法を確認します。

以下は、POSTのアクション作成メソッドです。

//POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
   try{
     //TODO: Add insert logic here
      return RedirectToAction("Index");
   }catch{
      return View();
   }
}

アクション作成メソッドを右クリックして、ビューの追加…を選択します

アクションを右クリックして作成

[ビューの追加]ダイアログが表示されます。

ビューの追加ダイアログを表示

上記のスクリーンショットでわかるように、デフォルト名はすでに言及されています。 ここで、[テンプレート]ドロップダウンから[作成]を選択し、[モデルクラス]ドロップダウンから[従業員]を選択します。

Create.cshtmlビューにデフォルトコードが表示されます。

@model MVCSimpleApp.Models.Employee
@{
   Layout = null;
}

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width"/>
      <title>Create</title>
   </head>

   <body>
      @using (Html.BeginForm()){
         @Html.AntiForgeryToken()
         <div class = "form-horizontal">
            <h4>Employee</h4>
            <hr/>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class = "form-group">
               @Html.LabelFor(model => model.Name, htmlAttributes:
                  new{ @class = "control-label col-md-2" })

               <div class = "col-md-10">
                  @Html.EditorFor(model => model.Name, new{ htmlAttributes =
                     new { @class = "form-control" } })

                  @Html.ValidationMessageFor(model => model.Name, "",
                     new{ @class = "text-danger" })
               </div>
            </div>

            <div class = "form-group">
               @Html.LabelFor(model => model.JoiningDate, htmlAttributes:
                  new{ @class = "control-label col-md-2" })

               <div class = "col-md-10">
                  @Html.EditorFor(model => model.JoiningDate, new{ htmlAttributes =
                     new { @class = "form-control" } })

                  @Html.ValidationMessageFor(model => model.JoiningDate, "",
                     new { @class = "text-danger" })
               </div>
            </div>

            <div class = "form-group">
               @Html.LabelFor(model => model.Age, htmlAttributes:
                  new { @class = "control-label col-md-2" })

               <div class = "col-md-10">
                  @Html.EditorFor(model => model.Age, new { htmlAttributes =
                     new { @class = "form-control" } })

                  @Html.ValidationMessageFor(model => model.Age, "", new{ @class = "text-danger" })
               </div>
            </div>

            <div class = "form-group">
               <div class = "col-md-offset-2 col-md-10">
                  <input type = "submit" value = "Create" class = "btn btn-default"/>
               </div>
            </div>

         </div>
      }

      <div>
         @Html.ActionLink("Back to List", "Index")
      </div>

   </body>
</html>

ユーザーがCreate Viewで値を入力すると、Request.Formと同様にFormCollectionで使用できます。 これらの値のいずれかを使用して、ビューから従業員情報を入力できます。

次のコードを使用して、FormCollectionを使用してEmployeeを作成しましょう。

//POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
   try {
      Employee emp = new Employee();
      emp.Name = collection["Name"];
      DateTime jDate;
      DateTime.TryParse(collection["DOB"], out jDate);
      emp.JoiningDate = jDate;
      string age = collection["Age"];
      emp.Age = Int32.Parse(age);
      empList.Add(emp);
      return RedirectToAction("Index");
   }catch {
      return View();
   }
}

このアプリケーションを実行し、このURL http://localhost:63004/Employee/を要求します。 次の出力が表示されます。

ローカルホストの従業員出力

ページ上部の[新規作成]リンクをクリックすると、次のビューが表示されます。

新しいリンクの作成

追加する別の従業員のデータを入力しましょう。

別の従業員データ

作成ボタンをクリックすると、新しい従業員がリストに追加されていることがわかります。

新しい従業員が追加されました

上記の例では、投稿されたすべての値をHTMLビューから取得し、これらの値をEmployeeプロパティにマッピングして、それらを1つずつ割り当てています。

この場合、投稿された値がModelプロパティと同じ形式でない場合はいつでも型キャストを行います。

これは手動バインディングとも呼ばれ、このタイプの実装は、単純なデータモデルや小規模なデータモデルにとってそれほど悪くないかもしれません。 ただし、巨大なデータモデルがあり、大量の型キャストが必要な場合は、ASP.NET MVCモデルバインディングのパワーと使いやすさを活用できます。

モデルバインディングで行ったのと同じ例を見てみましょう。

次のコードに示すように、Createメソッドのパラメーターを変更して、FormCollectionではなくEmployee Modelオブジェクトを受け入れる必要があります。

//POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee emp){
   try{
      empList.Add(emp);
      return RedirectToAction("Index");
   }catch{
      return View();
   }
}

モデルバインディングの魔法は、値を提供するHTML変数のIDに依存します。

従業員モデルの場合、HTML入力フィールドのIDは従業員モデルのプロパティ名と同じである必要があり、ビューの作成中にVisual Studioがモデルの同じプロパティ名を使用していることがわかります。

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

マッピングはデフォルトでプロパティ名に基づいています。 これは、これらのヘルパーメソッドがHTMLを生成し、モデルバインディングが機能するための適切な名前を持つため、HTMLヘルパーメソッドが非常に役立つ場所です。

このアプリケーションを実行し、URL http://localhost:63004/Employee/ を要求します。 次の出力が表示されます。

URLのリクエスト

ページ上部の[新規作成]リンクをクリックすると、次のビューが表示されます。

新しいリンクの作成をクリック

追加する別の従業員のデータを入力しましょう。

他の従業員のデータを入力

[作成]ボタンをクリックすると、ASP.Net MVCモデルバインディングを使用して、新しい従業員がリストに追加されていることがわかります。

MVCモデルバインディング