MVC EnumDropDownListFor with Enum Display attribute as value

I have an Enum with Display Description attribute,

public enum CSSColours
    {
        [Display(Description = "bg-green")]
        Green,

        [Display(Description = "bg-blue")]
        Blue,
    }

Now I want to bind this Enum to DropDownlist, showing the value of Enum (green, blue) in the display text of the drop-down list and Description as an element of Value (bg-green, bg-blue).

When will I link Dropdown to the EnumDropDownListForhelper method

@Html.EnumDropDownListFor(c => dm.BgColor)

It sets the value of the element to Enum (0, 1) and cannot find a way to set the value in the Display Description.

How to set a value in the Enum attribute Description attribute?

+4
source share
1 answer

You need to get the display name (DisplayAttribute) from Enum. Check below Example to set attribute value of Enum Display attribute

( )

public ActionResult Index()
        {   
            var enumDataColours = from CSSColours e in Enum.GetValues(typeof(CSSColours))
                           select new
                           {
                               ID = StaticHelper.GetDescriptionOfEnum((CSSColours)e),
                               Name = e.ToString()
                           };
            ViewBag.EnumColoursList = new SelectList(enumDataColours, "ID", "Name");
            return View();
        }

GetDescriptionOfEnum Description enum

public static class StaticHelper
    {
        public static string GetDescriptionOfEnum(Enum value)
        {
            var type = value.GetType();
            if (!type.IsEnum) throw new ArgumentException(String.Format("Type '{0}' is not Enum", type));

            var members = type.GetMember(value.ToString());
            if (members.Length == 0) throw new ArgumentException(String.Format("Member '{0}' not found in type '{1}'", value, type.Name));

            var member = members[0];
            var attributes = member.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false);
            if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' doesn't have DisplayAttribute", type.Name, value));

            var attribute = (System.ComponentModel.DataAnnotations.DisplayAttribute)attributes[0];
            return attribute.Description;
        }
    }

@Html.DropDownList("EnumDropDownColours", ViewBag.EnumColoursList as SelectList)

Enum

public enum CSSColours
    {
        [Display(Description = "bg-green")]
        Green,

        [Display(Description = "bg-blue")]
        Blue,
    }
+6

Source: https://habr.com/ru/post/1598642/


All Articles