ASP.Net, MVC C#| Get Enum Description Text


  ASP.Net - MVC C#| Get Enum Description Text


How to get enum description text, here is the code to achieve this.

Enum Code :

public enum TaskList
   {
       [Description("Open")]
       Open = 1,
       [Description("Work In Progress")]
       WIP = 2,
       [Description("Pending")]
       Pending = 3,
       [Description("Closed")]
       Closed = 4
   }

Code for get description:

using System.Reflection;
 
public class EnumList
    {
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();
 
            MemberInfo[] memInfo = type.GetMember(en.ToString());
 
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
 
                if (attrs != null && attrs.Length > 0)
                {
                    return ((System.ComponentModel.DescriptionAttribute)attrs[0]).Description;
                }
            }
 
            return en.ToString();
        }
    }

Code :

var taskList = from TaskList task in Enum.GetValues(typeof(TaskList))
                             select new
                             {
                                 ID = (int)task,
                                 Name = EnumList.GetDescription(task),
                                 Text = task.ToString()
                             };
 
            // To bind dropdown
            ViewBag.taskStatus = new SelectList(taskStatus, "ID""Name""tasks");
 
            // for sample how it works
            string strList = "";
            foreach (var item in taskList)
            {
                strList += item.Text + "  ";
            }

HTML :

@Html.DropDownList("taskid", (SelectList)ViewBag.taskStatus)

Enjoy !!!

:)

No comments:

Post a Comment