Reputation: 25
I have a dropdown control inside my view. Now i want it to have Description of enum as it's text. I am least worried about Id but i need text to be well formatted.
Upvotes: 1
Views: 1237
Reputation: 1915
Refer the following code.
public static List<EnumModel> GetEnumList<T>()
{
var enumValues = Enum.GetValues(typeof(T)).Cast<T>().Select(rentalType => new EnumModel()
{
Value = Convert.ToInt32(rentalType),
Name = GetDisplayName<T>(rentalType, false)
}).ToList();
return enumValues;
}
public static string GetDisplayName<T>(T value, bool isDisplayName)
{
if (value == null)
{
throw new ArgumentNullException("value", "Enum value Empty");
}
var type = value.GetType();
var field = type.GetField(value.ToString());
if (field == null)
{
return value.ToString();
}
var attributes = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
return attributes != null ? isDisplayName == true ? attributes.GetDescription() : attributes.Description : value.ToString();
}
public class EnumModel
{
/// <summary>
/// Gets or sets the value
/// </summary>
public int Value { get; set; }
/// <summary>
/// Gets or sets the name
/// </summary>
public string Name { get; set; }
}
You can get List<EnumModel>
as ENUM list with name and value.What you need to do is just make a List<SelectListitem>
from List<EnumModel>
Hope this helps.
Upvotes: 3
Reputation: 374
Use this code and bind with your dropdown-
public static List<SelectListItem> GetSelectList(Type enumType, String SelectedValue, Boolean IsValString = true)
{
Array values = Enum.GetValues(enumType);
List<SelectListItem> selectListItems = new List<SelectListItem>(values.Length);
foreach (var i in Enum.GetValues(enumType))
{
String name = Enum.GetName(enumType, i);
String desc = name;
FieldInfo fi = enumType.GetField(name);
var attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
String result = attributes.Length == 0 ? desc : ((DescriptionAttribute)attributes[0]).Description;
var selectItem = new SelectListItem()
{
Text = result,
Value = (IsValString) ? i.ToString() : ((Int32)i).ToString()
};
if ((SelectedValue != null) && (SelectedValue.Equals(selectItem.Value)))
{
selectItem.Selected = true;
}
selectListItems.Add(selectItem);
}
return selectListItems;
}
Upvotes: 2