ViewModelを使ってビューにオブジェクトを渡す
コントローラーからビューに値を渡す方法として、ViewData()やTempData()がありますが、これらは一つのパラメーターしか渡すことができません。
複数のパラメーターをビューに渡すには、ViewModelを使います。
以下に、ViewModelの作成手順と使い方を記述します。
ViewModelの作成
ViewModelは、クラスとして定義します。
ソリューションエクスプローラーからModelsフォルダにカーソルを合わせます。

右クリックして、「追加」→「クラス」を選択します。

クラスが選択されていることを確認して、名前を入力し、「追加」ボタンを押下します。
※クラス名は、コントローラーと違い自由に付けることができますが、ViewModelであることが分かる名称にします。

Modelsフォルダ配下に、クラスが作成されます。

ViewModelの編集
作成したViewModelのクラスをダブルクリックして、以下のように編集します。
ViewModelに定義する値は、ビューで使用するため「Public Property」にします。
1 2 3 4 5 |
Public Class HomeViewModel Public Property Name As String Public Property Address As String Public Property Birthday As Date End Class |
コントローラーの編集
ViewModelを作成したら、コントローラーでViewModelが使えるようにインスタンス化して、値を設定します。
View()の引数として、インスタンス化したViewModelを渡します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Imports System.Web.Mvc Namespace Controllers Public Class HomeController Inherits Controller Function Index() As ActionResult Dim vm As New HomeViewModel() vm.Name = "山田太郎" vm.Address = "東京都千代田区丸の内1-1-1" vm.Birthday = "2000/1/1" Return View(vm) End Function End Class End Namespace |
ビューの編集
ビューでViewModelを受け取るために、ViewModelの型を指定する必要があります。
ビューの先頭行に、以下のような記述をします。
@ModelType ViewModel名
ビューが受け取ったViewModelは、ビュー内でModelオブジェクトに紐づけられます。
1 2 3 4 5 6 7 8 |
@ModelType HomeViewModel @Code ViewData("Title") = "Index" End Code <h2>@Model.Name</h2> <h2>@Model.Address</h2> <h2>@Model.Birthday</h2> |
プログラムの実行
プログラムを実行すると、以下のようにコントローラーで設定した値が表示されます。
