ViewBag
/のような動的変数を避けViewData
、強い型に固執したいと思います。
ビューモデルを使用する
public class AssignDoctorViewModel
{
//Other Properties also
public IEnumerable<SelectListItem> Hospitals { set;get;}
public int SelectedHospital { set;get;}
}
そして、私のGET
Action メソッドでは、これを埋められたプロパティで返します
public ActionResult AssignDoctor
{
var vm=new AssignDoctorViewModel();
vm.Hospitals= new[]
{
new SelectListItem { Value = "1", Text = "Florance" },
new SelectListItem { Value = "2", Text = "Spark" },
new SelectListItem { Value = "3", Text = "Henry Ford" },
};
// can replace the above line with loading data from Data access layer.
return View(vm);
}
ViewModel クラスに強く型付けされたビューで
@model AssignDoctorViewModel
@using(Html.BeginForm())
{
@Html.DropDownListFor(x => x.SelectedHospital, Model.Hospitals, "Select..")
<input type="submit" value="save" />
}
Action メソッドで、プロパティHTTPPOST
にアクセスして Selected 値を取得できます。SelectedHospital
public ActionResult AssignDoctor(AssignDoctorViewModel model)
{
//check for model.SelectedHospital value
}