Binding Enums to Select Elements with Description Attributes in C#
When working with enum values in web aplpications, it's often necessary to display user-friendly descriptions rather than raw enum names. Here's an approach to bind enum values with they descriptions to HTML select elements.
1. Define the Enum with Descriptions
public enum OrganizationType
{
[Description("Government Institution")]
Government = 0,
[Description("Private Company")]
Private = 1,
[Description("Foreign Enterprise")]
Foreign = 2
}
2. Create Helper Methods
public static class EnumHelper
{
public static string GetEnumDescription(FieldInfo field)
{
var attributes = (DescriptionAttribute[])field
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : field.Name;
}
public static List<SelectListItem> GetEnumValues<T>() where T : Enum
{
return typeof(T)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Select(f => new SelectListItem
{
Text = GetEnumDescription(f),
Value = ((int)f.GetValue(null)).ToString()
}).ToList();
}
}
3. Controller Implementation
public JsonResult GetOrganizationTypes()
{
return Json(EnumHelper.GetEnumValues<OrganizationType>(),
JsonRequestBehavior.AllowGet);
}
4. Client-side Binding
function loadOrganizationTypes() {
$.ajax({
url: '/Controller/GetOrganizationTypes',
async: false,
success: function(data) {
const select = $('#orgType');
select.empty();
$.each(data, function(_, item) {
select.append($('<option>').val(item.Value).text(item.Text));
});
}
});
}