繁体   English   中英

如何获取枚举属性

[英]How get enum attributes

我创建模板编辑器。

@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

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

您可以编写一个自定义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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM