1

Inside razor view I'm rendering combobox with enum values like this

@Html.DropDownListFor(m => m.CarType, new SelectList(Enum.GetValues(typeof(CarTypeEnum))), 
      "Select value", new { @class = "form-control" })

public enum CarTypeEnum
{
  [StringValue("Car type one")]
   CarTypeOne = 1,

  [StringValue("Car type two")]
   CarTypeTwo = 2,
}

How can I use DropDownListFor helper to render StringValue inside combobox like Car type one instead of CarTypeOne

silver
  • 1,633
  • 1
  • 20
  • 32
user1765862
  • 13,635
  • 28
  • 115
  • 220
  • Also refer the answers to [this question](http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc) –  Dec 20 '16 at 09:02

1 Answers1

1

You can use the Display attribute provided in C#. Which would be something like this:

public enum CarTypeEnum
{
[Display(Name="Car type one")]
CarTypeOne = 1,
[Display(Name="Car type two")]
CarTypeTwo
}

You also just have to provide a value to your first enum only. Rest will be genrated automatically.

I also have an enum extension to put the text provided in the display attribute als text in your dropdownlist:

public static class EnumExtensions
    {/// <summary>
     ///     A generic extension method that aids in reflecting 
     ///     and retrieving any attribute that is applied to an `Enum`.
     /// </summary>
        public static TAttribute GetAttribute<TAttribute>(this Enum enumValue)
                where TAttribute : Attribute
        {
            return enumValue.GetType()
                            .GetMember(enumValue.ToString())
                            .First()
                            .GetCustomAttribute<TAttribute>();
        }
    }

Usage goes as follow:

new SelectListItem
            {
                Text = CarTypeEnum.CarTypeOne.GetAttribute<DisplayAttribute>().Name
            }
rubenj
  • 118
  • 1
  • 6