Asp.Net MVC中如何使用DropDownListFor2014-08-27在Asp.Net MVC中可以用DropDownListFor的方式来让用户选择已定列表中的一个数值。用法不复杂,这里简单做一个记录。首先我们要定义一个 Model,用户在 DropDownList 中选择指定的值赋给属性ReadyTimeHour
public class EricSunModel{public string ReadyTimeHour { get; set; }}Model定义完毕之后,接下来处理Controller的逻辑【注:这里用了ViewData来记录DropDownList中所要显示的所有列表数值】
public ActionResult EricSunAction(){EricSunModel esModel = new EricSunModel();esModel.ReadyTimeHour = "00";GenerateReadyTimeViewData();return View(esModel);}private void GenerateReadyTimeViewData(){ViewData["HourList"] = GetTimeHourList();}private List<SelectListItem> GetTimeHourList(){List<SelectListItem> hourList = new List<SelectListItem>();for (int i = 0; i < 24; i++){if (i < 10){hourList.Add(new SelectListItem { Text = "0" + i.ToString(), Value = "0" + i.ToString() });}else{hourList.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });}}return hourList;}接下来我们在
View中可以用下面一行代码来绑定
DropDownList【注:第一个参数为绑定
Model中的属性,即-->要为此属性赋值】【注:第二个参数为
DropDownList的所有数据源】
@Html.DropDownListFor(m => m.ReadyTimeHour, ViewData["HourList"] as List<SelectListItem>)
截图如下所示