MVC中枚举绑定到DropDownList
枚举
/// 电脑部件枚举
///</summary>
public enum ComputerPartsEnum
{
[Description("键盘")]
Keyboard = 1,
[Description("鼠标")]
Mouse = 2,
[Description("显示器")]
Monitor = 3,
[Description("机箱")]
Chassis = 4,
[Description("摄像头")]
Camera = 5
}
枚举转换类
{
/// <summary>
/// 获取枚举的描述文本
/// </summary>
/// <param name="e">枚举成员</param>
/// <returns></returns>
public static string GetEnumDescription(object e)
{
//获取字段信息
System.Reflection.FieldInfo[] ms = e.GetType().GetFields();
Type t = e.GetType();
foreach (System.Reflection.FieldInfo f in ms)
{
//判断名称是否相等
if (f.Name != e.ToString()) continue;
//反射出自定义属性
foreach (Attribute attr in f.GetCustomAttributes(true))
{
//类型转换找到一个Description,用Description作为成员名称
System.ComponentModel.DescriptionAttribute dscript = attr as System.ComponentModel.DescriptionAttribute;
if (dscript != null)
return dscript.Description;
}
}
//如果没有检测到合适的注释,则用默认名称
return e.ToString();
}
/// <summary>
/// 把枚举的描述和值绑定到DropDownList
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static List<SelectListItem> GetCategorySelectList(Type enumType)
{
List<SelectListItem> selectList = new List<SelectListItem>();
selectList.Add(new SelectListItem { Text = "--请选择类型--", Value = "0", Selected = true });
foreach (object e in Enum.GetValues(enumType))
{
selectList.Add(new SelectListItem { Text = GetEnumDescription(e), Value = ((int)e).ToString() });
}
return selectList;
}
}
Controller
{
//把枚举绑定到DropDownList
ViewBag.computerParts =EnumCOM.GetCategorySelectList(typeof(ComputerPartsEnum));
ViewBag.part = EnumCOM.GetEnumDescription(ComputerPartsEnum.Keyboard); //键盘
return View();
}
View
@Html.DropDownList("ddl_Computer", @ViewBag.computerParts as IEnumerable<SelectListItem>)