0

我创建模板编辑器。

@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

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

4

2 回答 2

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)
于 2013-03-13T12:12:03.830 回答
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 中根据您的需要更改上述组合框代码。

于 2013-03-13T12:25:13.107 回答