如何获取枚举属性

本文关键字:枚举 属性 获取 何获取 | 更新日期: 2023-09-27 18:03:45

创建模板编辑器。

@model dynamic

@{
    var modelMetadata = Html.GetModelMetadataFor(model => model);
    var selectList = ReflectionHelpers.GetSelectListByEnumFor(modelMetadata);
    String name = //get property name;
}

with get modelMetadata all right

但是我不明白如何获得属性。

在我使用这个代码之前:

Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
IEnumerable<SelectListItem> items = values.Select(value =>
    new SelectListItem
    {
        Text = GetEnumDescription(value),
        Value = value.ToString(),
        Selected = value.Equals(metadata.Model)
    });

但是在这个时候我不明白怎么拿TEnum

我的问题是:"如何创建选择列表从enum"

如何获取枚举属性

你可以编写一个自定义html帮助器,它将为当前模型生成一个下拉列表(当然假设这个模型是一个enum):

public static class HtmlExtensions
{
    public static IHtmlString DropDownListForEnum(this HtmlHelper htmlHelper)
    {
        var model = htmlHelper.ViewData.Model;
        if (model == null)
        {
            throw new ArgumentException("You must have a model in order to use this method");
        }
        var enumType = model.GetType();
        if (!enumType.IsEnum)
        {
            throw new ArgumentException("This method works only with enum types.");
        }
        var fields = enumType.GetFields(
            BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
        );
        var values = Enum.GetValues(enumType).OfType<object>();
        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 };
        var selectList = new SelectList(items, "Id", "Name", model);
        return htmlHelper.DropDownList("", selectList);
    }
}

,然后在模板中调用这个帮助器:

@Html.DropDownListForEnum()

更新:

如果你想把所有的代码都放在模板中你也可以这样做:

@using System.ComponentModel
@using System.Reflection
@using System.Linq;
@model object
@{
    var model = Html.ViewData.Model;
    if (model == null)
    {
        throw new ArgumentException("You must have a model in order to use this template");
    }
    var enumType = model.GetType();
    if (!enumType.IsEnum)
    {
        throw new ArgumentException("This method works only with enum types.");
    }
    var fields = enumType.GetFields(
        BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
    );
    var values = Enum.GetValues(enumType).OfType<object>();
    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 };
    var selectList = new SelectList(items, "Id", "Name", model);
}
@Html.DropDownList("", selectList)

不幸的是,我不知道asp.net是如何工作的,但在。net框架内,我使用这个扩展方法:

public static IList<KeyValuePair<T, string>> ToList<T>() where T : struct
{
    var type = typeof(T);
    if (!type.IsEnum)
    {
        throw new ArgumentException("T must be an enum");
    }
    return (IList<KeyValuePair<T, string>>)
            Enum.GetValues(type)
                .OfType<T>()
                .Select(e =>
                {
                    var asEnum = (Enum)Convert.ChangeType(e, typeof(Enum));
                    return new KeyValuePair<T, string>(e, GetEnumDescription(asEnum));
                })
                .ToArray();
}

在winforms中,我可以使用它作为一个组合框,只需调用:

var pairs = EnumExtension.ToList<ContenAlignment>();
comboBoxFormat.DataSource = pairs;
comboBoxFormat.ValueMember = "Key";
comboBoxFormat.DisplayMember = "Value";

也许您可以在asp.net中根据您的需要更改上述组合框代码。