在ASP.NET MVC中可以用DropDownListFor的方式来让用户选择已定列表中的一个数值。
注:重点是要将DropDownList的数据源转换成IEnumerable<SelectListItem>类型的结合;
SelectListItem类在System.Web.MVC命名空间下,其成员如下:
1 //处理State,将IEnumerable<State>集合转换为IEnumerable<SelectListItem>集合 2 public IEnumerable<SelectListItem> GetStates() 3 { 4 return _usStateService.GetStates().OrderBy(c => c.StateAbbreviation).Select(state => new SelectListItem 5 { 6 Text = state.StateAbbreviation, 7 Value = state.StateAbbreviation 8 }); 9 }
使用如下示例:
1 public class EricSunModel 2 { 3 public string ReadyTimeHour { get; set; } 4 }
1 public ActionResult EricSunAction() 2 { 3 EricSunModel esModel = new EricSunModel(); 4 esModel.ReadyTimeHour = "00"; 5 6 GenerateReadyTimeViewData(); 7 8 return View(esModel); 9 } 10 11 private void GenerateReadyTimeViewData() 12 { 13 ViewData["HourList"] = GetTimeHourList(); 14 } 15 16 //这里要对集合进行处理,因为第二个参数必须是IEnumerable<SelectListItem> 类型的集合 17 private List<SelectListItem> GetTimeHourList() 18 { 19 List<SelectListItem> hourList = new List<SelectListItem>(); 20 21 for (int i = 0; i < 24; i++) 22 { 23 if (i < 10) 24 { 25 hourList.Add(new SelectListItem { Text = "0" + i.ToString(), Value = "0" + i.ToString() }); 26 } 27 else 28 { 29 hourList.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() }); 30 } 31 } 32 33 return hourList; 34 }
1 @Html.DropDownListFor(m => m.ReadyTimeHour, ViewData["HourList"] as List<SelectListItem>)
1 @Html.DropDownListFor(m => m.ReadyTimeHour, ViewData["HourList"] as List<SelectListItem>, "---Select---")
原文:http://www.cnblogs.com/sunshineground/p/4372538.html