如何获得枚举属性

时间:2013-03-13 11:41:42

标签: c# asp.net-mvc

我创建了模板编辑器。

@model dynamic


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

使用get modelMetadata可以

但是如何得到我不理解的属性。

在我使用此代码之前:

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怎么用

我的问题是:“如何从枚举中创建选择列表”

2 个答案:

答案 0 :(得分:1)

您可以编写一个自定义html帮助程序,它将生成当前模型的下拉列表(假设此模型当然是枚举):

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)

答案 1 :(得分:0)

不幸的是我不知道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中根据需要更改上面的组合框代码。