SelectListItem Helper to create selectlistitems from enum

first, we create a extension method to get the descriptions of enum values.

public static string ToDescription<T>(this T enumValue)
            where T : struct, IConvertible, IComparable, IFormattable // Criteria for Enums
        {
            var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
            var attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).Cast<DescriptionAttribute>().ToList();
            return attributes.Any() ? attributes.First().Description : enumValue.ToLabel();
        }

second, create the selectlistitems from the enum.

public static List<SelectListItem> GetItemsForEnum<TEnum>(int? selectedValue = null, string defaultText = "")
            where TEnum : struct, IConvertible, IComparable, IFormattable // Criteria for Enums
        {
            var results = new List<SelectListItem>();
            var values = Enum.GetValues(typeof (TEnum));
 
            if (!string.IsNullOrEmpty(defaultText ))
                results.Add(new SelectListItem { Text = defaultText , Value = "" });
 
            foreach (var value in values)
            {
                var name = ((TEnum)value).ToDescription();
                var selected = (selectedValue != null) && selectedValue.Equals((int)value);
                results.Add(new SelectListItem { Text = name, Value = ((int)value).ToString(), Selected = selected });
            }
            return results;
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s