public static class EnumKit
{
#region
///
///
///
///
/// ( 。 : / )
/// ( 。 : / )
///
public static IList ToSelectList(Type enumType
, string firstText = " "
, string firstValue = "-1")
{
IList listItem = new List();
if (enumType.IsEnum)
{
AddFirst(listItem, firstText, firstValue);
Array values = Enum.GetValues(enumType);
if (null != values && values.Length > 0)
{
foreach (int item in values)
{
listItem.Add(new SelectListItem { Value = item.ToString(), Text = Enum.GetName(enumType, item) });
}
}
}
else
{
throw new ArgumentException(" !");
}
return listItem;
}
static void AddFirst(IList listItem, string firstText, string firstValue)
{
if (!string.IsNullOrWhiteSpace(firstText))
{
if (string.IsNullOrWhiteSpace(firstValue))
firstValue = "-1";
listItem.Add(new SelectListItem { Text = firstText, Value = firstValue });
}
}
///
///
///
///
///
public static IList ToSelectListByDesc(
Type enumType
, string firstText = " "
, string firstValue = "-1"
)
{
IList listItem = new List();
if (enumType.IsEnum)
{
AddFirst(listItem, firstText, firstValue);
string[] names = Enum.GetNames(enumType);
names.ToList().ForEach(item =>
{
string description = string.Empty;
var field = enumType.GetField(item);
object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //
description = arr != null && arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : item; //
listItem.Add(new SelectListItem() { Value = ((int)Enum.Parse(enumType, item)).ToString(), Text = description });
});
}
else
{
throw new ArgumentException(" !");
}
return listItem;
}
#endregion
#region
///
///
///
///
///
public static string GetDescription(this Enum enumValue)
{
string value = enumValue.ToString();
FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (objs == null || objs.Length == 0) return value;
System.ComponentModel.DescriptionAttribute attr = (System.ComponentModel.DescriptionAttribute)objs[0];
return attr.Description;
}
#endregion
}
:
public ActionResult Index()
{
IList listItem = EnumKit.ToSelectList(typeof(OrderStatus), " ");
ViewBag.SelectListItem = listItem;
IList SelectListItemDesc = EnumKit.ToSelectListByDesc(typeof(OrderStatus));
ViewBag.SelectListItemDesc = SelectListItemDesc;
//
string sendHuo = OrderStatus. .GetDescription();
return View();
}
コード 、ダウンロードをクリック