C# 枚举转换selectlistitem 及 MVC @Html.DropDownListFor() 调用详细
枚举转换方法
/// <summary> /// 根据枚举返回 List<SelectListItem> /// </summary> /// <param name="enumType"></param> /// <param name="withEmpty">true ---请选择--- </param> /// <param name="topValue">如果值不为0 则按枚举值选择</param> /// <returns></returns> public static List<SelectListItem> GetEnumDataSource(Type enumType, bool withEmpty, int topValue = 0) { List<SelectListItem> list = new List<SelectListItem>(); if (withEmpty) { list.Add(new SelectListItem { Value = topValue.ToString(), Text = "--请选择--", Selected = true }); } FieldInfo[] fields = enumType.GetFields(); foreach (FieldInfo item in fields) { if (!item.FieldType.IsEnum) continue; int value = (int)item.GetValue(null); if (value < 0) continue; string text = string.Empty; object[] attrs = item.GetCustomAttributes(false); foreach (object attr in attrs) { DescriptionAttribute des = attr as DescriptionAttribute; if (des == null) { continue; } else { text = des.Description; } } if (topValue == value) { list.Add(new SelectListItem { Value = value.ToString(), Text = text, Selected = true }); } else { list.Add(new SelectListItem { Value = value.ToString(), Text = text }); } } return list; }
Controller:
var selectLists = EnumExtension.GetEnumDataSource(typeof(UserType), false, (int)result.Item.RoleId); TempData["RoleSalesList"] = selectLists;
View
@Html.DropDownListFor(model => model.RoleId , TempData["RoleSalesList"] as IEnumerable< SelectListItem>, new { @class = "form-control" } )
精神共享,智慧共融!