ControllerからViewへの値の受け渡し
ContorollerからViewへの値の受け渡しは以下の二つの方法がある。
ViewData["hogehoge"] = data;
・ViewBag.hogehoge = data;
ViewBagはMVC3からサポートされているものでMVC2以前のものはViewDataのみしか選択肢がなかった。
Contoroller側での扱いの違いは上記の通りだが、View側での取り扱いが異なると、どうなるかと思いチェックしてみた。
Controllerには以下のメソッドを追加した
public ActionResult View1() { ViewBag.Test = "this is a test."; ViewData["Test2"] = "this is a test2."; return View(); }
そしてこのControllerのテストメソッドに以下を追加した。
(こうすることでController内でViewData,ViewBagが設定されているかを確かめることができる)
[TestMethod] public void View1() { HomeController controller = new HomeController(); ViewResult result = (ViewResult)controller.View1(); Assert.AreEqual("this is a test.",result.ViewBag.Test); Assert.AreEqual("this is a test2.",result.ViewBag.Test2); }
結果から、ViewDataを使用したものであってもViewBagから参照可能であることが分かった。
Viewを記述する際はViewDataを使用せず、ViewBagを使用すると良い。
(ViewBagならば、View側で@ViewBag.hogehogeとするだけで利用できる)