1、下面代码包含了三种绑定DropDownList的方法
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SupermarketManagement.Controllers { public class HtmlControlsController : Controller { //单位枚举 public enum Units { 米, 厘米, 毫米, 微米 } /// <summary> /// DropDownList 控件 /// </summary> /// <returns></returns> public ActionResult DropDownListIndex() { //1、第一种表现形式(性别) List<SelectListItem> sexItems = new List<SelectListItem>(); sexItems.Add(new SelectListItem { Text = "请选择", Value = "0", Selected = true }); sexItems.Add(new SelectListItem { Text = "男", Value = "1" }); sexItems.Add(new SelectListItem { Text = "女", Value = "2" }); ViewBag.Sex = sexItems; //2、第二种表现形式 var values = Enum.GetValues(typeof(Units)).Cast<Units>(); var items = from value in values select new SelectListItem { Text = value.ToString(),Value=value.ToString() }; ViewBag.Unit = items;//2.1 ViewBag.UnitEx = Units.米.ToSelectListItem("毫米");//2.2:这里用的扩展方法 //3、第三种表现形式选中(用户更新,展示) List<SelectListItem> list = new List<SelectListItem>() { new SelectListItem(){Value="Man",Text="Man"}, new SelectListItem(){Value="Female",Text="Female"} }; ViewBag.Gender = new SelectList(list, "Value", "Text","Female"); return View(); } } //枚举扩展方法 public static class ExSelectListItem { /// <summary> /// 显示所有列表 /// </summary> /// <param name="valueEnum"></param> /// <returns></returns> public static IEnumerable<SelectListItem> ToSelectListItem(this Enum valueEnum) { var values = Enum.GetValues(valueEnum.GetType()); var result = from int value in values select new SelectListItem { Text = Enum.GetName(valueEnum.GetType(), value), Value = value.ToString() }; return result; } /// <summary> /// 选中的列表项 /// </summary> /// <param name="valueEnum"></param> /// <param name="selectName"></param> /// <returns></returns> public static List<SelectListItem> ToSelectListItem(this Enum valueEnum, string selectName) { return (from int value in Enum.GetValues(valueEnum.GetType()) select new SelectListItem { Text = Enum.GetName(valueEnum.GetType(), value), Value = Enum.GetName(valueEnum.GetType(), value), Selected = Enum.GetName(valueEnum.GetType(), value) == selectName ? true : false }).ToList(); } } }
2、Views 代码
<body> <p> 一、第一种表现形式<br /> 性别:@Html.DropDownList("Sex") </p> <p> 二、第二种表现形式<br /> 单位:@Html.DropDownList("Unit")<br /> 单位:@Html.DropDownList("UnitEx") </p> <p> 三、第三种表现形式<br /> 性别:@Html.DropDownList("Gender") </p> </body>
3、结果: