C#.NET MVC 枚举转dictionary自动装载生成下拉框
/// <summary> /// 枚举转SelectListItem /// </summary> public class Enum_Helper { /// <summary> /// 枚举转字典集合 /// </summary> /// <typeparam name="T">枚举类名称</typeparam> /// <param name="keyDefault">默认key值</param> /// <param name="valueDefault">默认value值</param> /// <returns>返回生成的字典集合</returns> public static List<SelectListItem> GetSelectListItem<T>(object keyDefault) { List<SelectListItem> dicEnum = new List<SelectListItem>(); Type enumType = typeof(T); if (!enumType.IsEnum) return dicEnum; string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组 foreach (var item in fieldstrs) { string description = string.Empty; var field = enumType.GetField(item); object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组 if (arr != null && arr.Length > 0) description = ((DescriptionAttribute)arr[0]).Description; //属性描述 else description = item; //描述不存在取字段名称 //判断是否添加默认选项 if (keyDefault != null && keyDefault.Equals(Enum.Parse(enumType, item))) { dicEnum.Add(new SelectListItem() { Text = description, Selected = true, Value = Enum.Parse(enumType, item).ToString() }); } else { dicEnum.Add(new SelectListItem() { Text = description, Value = Enum.Parse(enumType, item).ToString() }); } } return dicEnum; } }
调用 Enum_Helper.GetSelectListItem<HealthLederses.Auditing>(input.HealthLedersAuditDto.Status);
更多例子参考:http://blog.csdn.net/shuizhaoshui/article/details/51412762
文章属于个人工作备忘录,欢迎指正...