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"}]