我宁愿避免像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 方法中,您可以通过访问PropertyHTTPPOST
来获取 Selected 值SelectedHospital
public ActionResult AssignDoctor(AssignDoctorViewModel model)
{
//check for model.SelectedHospital value
}