Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Binding Enums to Select Elements with Description Attributes in C#

Tech May 7 3

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));
            });
        }
    });
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.