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

1
  • Also refer the answers to this question Commented Dec 20, 2016 at 9:02

1 Answer 1

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
            }
Sign up to request clarification or add additional context in comments.

2 Comments

This cannot be applied cause .First() inside provided EnumExtensions reports an error. Did you tried this before posting here?
Yes, I'm using it in my web application

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.