How to get the values of an enum into a SelectList

前端 未结 12 948
醉梦人生
醉梦人生 2020-12-13 11:58

Imagine I have an enumeration such as this (just as an example):

public enum Direction{
    Horizontal = 0,
    Vertical = 1,
    Diagonal = 2
}
12条回答
  •  -上瘾入骨i
    2020-12-13 12:37

    I had many enum Selectlists and, after much hunting and sifting, found that making a generic helper worked best for me. It returns the index or descriptor as the Selectlist value, and the Description as the Selectlist text:

    Enum:

    public enum Your_Enum
    {
        [Description("Description 1")]
        item_one,
        [Description("Description 2")]
        item_two
    }
    

    Helper:

    public static class Selectlists
    {
        public static SelectList EnumSelectlist(bool indexed = false) where TEnum : struct
        {
            return new SelectList(Enum.GetValues(typeof(TEnum)).Cast().Select(item => new SelectListItem
            {
                Text = GetEnumDescription(item as Enum),
                Value = indexed ? Convert.ToInt32(item).ToString() : item.ToString()
            }).ToList(), "Value", "Text");
        }
    
        // NOTE: returns Descriptor if there is no Description
        private static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes != null && attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }
    }
    

    Usage: Set parameter to 'true' for indices as value:

    var descriptorsAsValue = Selectlists.EnumSelectlist();
    var indicesAsValue = Selectlists.EnumSelectlist(true);
    

提交回复
热议问题