使用AttributeDescription字段下拉列表枚举ASP.NET MVC [英] Drop-Down List Enum ASP.NET MVC Using AttributeDescription Field

查看:246
本文介绍了使用AttributeDescription字段下拉列表枚举ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:<一href=\"http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc/694361#694361\">How你在ASP.NET MVC枚举创建一个DropDownList?

我想这样做同样的事情,但用AttributeDescription领域从我的枚举,例如:

I want to do the exact same thing, except using the AttributeDescription field from my enum, for example:

[DescriptionAttribute("1 Star")] OneStar = 1,
[DescriptionAttribute("2 Stars")] TwoStar = 2,
[DescriptionAttribute("3 Stars")] ThreeStar = 3,
[DescriptionAttribute("4 Stars")] FourStar = 4

在之前给出的链接将下降的文本字段中显示ONESTAR下来,而我愿意看到1星的解决方案。我已经看到了有关这几个职位,但他们的解决方案是相当冗长。

The solution given in the prior link will show "OneStar" in the text field of a drop down, whereas I'd want to see "1 Star". I've seen a few posts relating to this, but their solutions are quite verbose.

推荐答案

您可以尝试线中的内容:

You may try something among the lines:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
    var enumType = typeof(TEnum);
    var fields = enumType.GetFields(
        BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
    );
    var values = Enum.GetValues(enumType).OfType<TEnum>();
    var items = 
        from value in values
        from field in fields
        let descriptionAttribute = field
            .GetCustomAttributes(
                typeof(DescriptionAttribute), true
            )
            .OfType<DescriptionAttribute>()
            .FirstOrDefault()
        let description = (descriptionAttribute != null)
            ? descriptionAttribute.Description 
            : value.ToString()
        where value.ToString() == field.Name
        select new { Id = value, Name = description };
    return new SelectList(items, "Id", "Name", enumObj);
}

这篇关于使用AttributeDescription字段下拉列表枚举ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆