相关疑难解决方法(0)

如何从ASP.NET MVC中的枚举创建下拉列表?

我正在尝试使用Html.DropDownList扩展方法,但无法弄清楚如何将它与枚举一起使用.

假设我有一个这样的枚举:

public enum ItemTypes
{
    Movie = 1,
    Game = 2,
    Book = 3
}
Run Code Online (Sandbox Code Playgroud)

如何使用Html.DropDownList扩展方法创建包含这些值的下拉列表?

或者我最好的办法是简单地创建一个for循环并手动创建Html元素?

c# asp.net asp.net-mvc

653
推荐指数
21
解决办法
34万
查看次数

从Description属性获取枚举

可能重复:
通过其描述属性查找枚举值

我有一个通用的扩展方法,它Description从以下方式获取属性Enum:

enum Animal
{
    [Description("")]
    NotSet = 0,

    [Description("Giant Panda")]
    GiantPanda = 1,

    [Description("Lesser Spotted Anteater")]
    LesserSpottedAnteater = 2
}

public static string GetDescription(this Enum value)
{            
    FieldInfo field = value.GetType().GetField(value.ToString());

    DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                as DescriptionAttribute;

    return attribute == null ? value.ToString() : attribute.Description;
}
Run Code Online (Sandbox Code Playgroud)

所以我可以......

string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
Run Code Online (Sandbox Code Playgroud)

现在,我正试图在另一个方向上找出等效函数,比如......

Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
Run Code Online (Sandbox Code Playgroud)

.net c# enums attributes

206
推荐指数
4
解决办法
18万
查看次数

将枚举绑定到MVC 4中的DropDownList?

我一直在寻找将Enums绑定到DropDowns的常用方法是通过辅助方法,这对于看似简单的任务似乎有点霸道.

将Enums绑定到ASP.Net MVC 4中的DropDownLists的最佳方法是什么?

html data-binding asp.net-mvc enums drop-down-menu

25
推荐指数
5
解决办法
6万
查看次数