问题的枚举下拉列表

时间:2014-02-11 15:51:10

标签: asp.net-mvc-4 enums html.dropdownlistfor

我已经阅读了一个可能的解决方案,但是需要大量的重写,可能的解决方案是here,但是如果我只是一个可行的话就没有任何意义在我的dropdownlistfor中关闭几个词。

我的下拉列表存在问题,因为这对我来说很新鲜:

@Html.DropDownListFor(model => model.pageID, new SelectList (Enum.GetNames(typeof(PageIndex)), EnumHelper.GetSelectedItemList<PageIndex>().SelectedValue))

当下拉列出文本值时,尝试获取我的枚举值的“描述”,然后在POST时将一个整数值返回给数据库。

这是我的枚举:

public enum PageIndex : int
{
    [Description("Developmental Disabilities Tip Sheet")]
    ddTipSheets = 1,

    [Description("Hiiiiiiiiiiiiiiiiiiii")]
    Example1 = 2,

    [Description("I don't know what I'm doing")]
    Example2 = 3
}; 

和我的EnumHelper:

public class EnumHelper
{
    public static SelectList GetSelectedItemList<T>() where T : struct
    {
        T t = default(T);
        if (!t.GetType().IsEnum) { throw new ArgumentNullException("Please make sure that T is of Enum Type"); }

        var nameList = t.GetType().GetEnumNames();

        int counter = 0;

        Dictionary<int, String> myDictionary = new Dictionary<int, string>();
        if (nameList != null && nameList.Length > 0)
        {
            foreach (var name in nameList)
            {
                T newEnum = (T) Enum.Parse(t.GetType(), name);
                string description = getDescriptionFromEnumValue(newEnum as Enum);

                if (!myDictionary.ContainsKey(counter))
                {
                    myDictionary.Add(counter, description);
                }
                counter++;
            }

            counter = 0;

            return new SelectList(myDictionary, "Key", "Value");
        }

        return null;
    }

    private static string getDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute descriptionAttribute =
            value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;

        return descriptionAttribute == null ? 
            value.ToString() : descriptionAttribute.Description;
    }
}

0 个答案:

没有答案