2

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.

Community
  • 1
  • 1
Kieran Senior
  • 17,960
  • 26
  • 94
  • 138

2 Answers2

4

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);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Instead of defaulting to value.ToString() when no Desc attr my version uses field.Name: let description = (descriptionAttribute!=null)?descriptionAttribute.Description : field.Name.Replace("_", " ") – yzorg Dec 05 '12 at 16:28
0

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)
Community
  • 1
  • 1
Nick Evans
  • 3,279
  • 2
  • 25
  • 21