How to enumerate an ENUM (C#)

Goal:

You have a C# ENUM and for some reason you would like to enumerate it. Perhaps you would like to return the enumerated list to the client’s ajax call rather than calling the DB table that represents the ENUM. For example you may have invoice statuses and want to build an anonymous list.

Result:

C# class:

public enum InvoiceStatus
{
    [Display(Name = "OPEN")]
    Open = 1,
    [Display(Name = "CANCELLED")]
    Cancel = 2,
    [Display(Name = "POSTED")]
    Posted = 3,
    [Display(Name = "VOIDED")]
    Void = 4,
    [Display(Name = "SUBMITTED")]
    Submitted = 5
}

MVC Controller:

[Route("getinvoiceStatuses")]

[HttpGet]

public IList<object> GetInvoiceStatuses()

{

var list = new List<object>();

foreach (var status in Enum.GetValues(typeof(InvoiceStatus)))
{
    list.Add(new
    {
        Id = (int)status,
        Description = status.ToString()
    });
}

return list;

}

JSON:

[{"Id":1,"Description":"Open"},

{"Id":2,"Description":"Cancel"},

{"Id":3,"Description":"Posted"},

{"Id":4,"Description":"Void"},

{"Id":5,"Description":"Submitted"}]

Print | posted @ Tuesday, November 15, 2016 3:18 PM

Comments on this entry:

Gravatar # apps for sys
by pizap at 11/16/2016 12:22 AM

Thank you for bringing more information to this topic for me. I’m truly grateful and really impressed. Really appreciate for your amazing article. Thank you for this valuable information.
Gravatar # B.ed Colleges admission in rohtak 2017
by DK Shingh at 11/16/2016 4:55 AM

hello Sir/mam
I like your site its is very cool....
B.ed Syllabus Haryana 2017
Post A Comment
Title:
Name:
Email:
Comment:
Verification: