Drop-Down List Enum ASP.NET MVC Using AttributeDes

2020-04-16 03:10发布

问题:

Based on this post: How do you create a dropdownlist from an enum in ASP.NET MVC?

I want to do the exact same thing, except using the AttributeDescription field from my enum, for example:

[DescriptionAttribute("1 Star")] OneStar = 1,
[DescriptionAttribute("2 Stars")] TwoStar = 2,
[DescriptionAttribute("3 Stars")] ThreeStar = 3,
[DescriptionAttribute("4 Stars")] FourStar = 4

The solution given in the prior link will show "OneStar" in the text field of a drop down, whereas I'd want to see "1 Star". I've seen a few posts relating to this, but their solutions are quite verbose.

回答1:

You may try something among the lines:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
    var enumType = typeof(TEnum);
    var fields = enumType.GetFields(
        BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
    );
    var values = Enum.GetValues(enumType).OfType<TEnum>();
    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 };
    return new SelectList(items, "Id", "Name", enumObj);
}


回答2:

The best solution I found for this was combining this blog with this answer. This makes both the view and model very readable and maintainable.

See my full answer here.

Model:

public enum YesPartialNoEnum
{
    [Description("Yes definitely")]
    Yes,
    [Description("No way!")]
    No
}

//........

[Display(Name = "The label for my dropdown list")]
public virtual Nullable<YesPartialNoEnum> CuriousQuestion{ get; set; }

//........

View:

@Html.ValidationMessageFor(model => model.CuriousQuestion)