如何使用"pretty names"将枚举绑定到 ASP.NET 下拉列表中列表



我知道如何将枚举值绑定到DropDownList,但我想使用"漂亮的名字"而不是枚举值。

例如我描述enum:

    public enum ContainerStatus
    {
        [Display(Description = "Container processed")]
        Processed,
        [Display(Description = "Container ready to ship")]
        ReadyToShip,
        [Display(Description = "Container sent")]
        Sent
    }

我想要显示DisplayAttribute值而不是enum值。你能帮我吗?

尝试通用实现:

public static List<KeyValuePair<string, string>> EnumToList<T>() where T: Enum
    {
        var pInfos = typeof(T).GetFields();
        List<KeyValuePair<string, string>> displayList = new List<KeyValuePair<string, string>>();
        foreach (var pi in pInfos)
        {
            if (pi.FieldType == typeof(int)) continue;
            var attr = pi.GetCustomAttributes(typeof(DisplayAttribute), false);
            if (attr != null && attr.Length > 0)
            {
                var key = pi.Name;
                var value = (attr[0] as DisplayAttribute).Description;
                KeyValuePair<string, string> listItem = new KeyValuePair<string, string>(key, value);
                displayList.Add(listItem);
            }
            else
            {
                KeyValuePair<string, string> listItem = new KeyValuePair<string, string>(pi.Name, pi.Name);
                displayList.Add(listItem);
            }
        }
        return displayList;
    }
数据绑定方法:
protected void Page_Load(object sender, EventArgs e)
{
     var dataSource = EnumToList<ContainerStatus>();
     dropDownList.DataSource = dataSource;
     dropDownList.DataValueField = "Key";
     dropDownList.DataTextField = "Value";
     dropDownList.DataBind();
}

您需要创建一个类来读取Display属性。

完整的源代码如下。

public enum ContainerStatus
{
    [Display(Description = "Container processed")]
    Processed,
    [Display(Description = "Container ready to ship")]
    ReadyToShip,
    [Display(Description = "Container sent")]
    Sent
}
public static class EnumExtensions
{
    public static string Description(this Enum value)
    {
        var enumType = value.GetType();
        var field = enumType.GetField(value.ToString());
        var attributes = field.GetCustomAttributes(typeof(DisplayAttribute),
                                                   false);
        return attributes.Length == 0
            ? value.ToString()
            : ((DisplayAttribute)attributes[0]).Description;
    }
}
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {       
        var values = Enum.GetValues(typeof(ContainerStatus)).Cast<ContainerStatus>();
        foreach (var v in values)
        {
            DropDownList1.Items.Add(v.Description());                
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新