Reputation: 63
I want to get the EnumMember's Value statically. It works if I pass fill out my model, as shown below.
LibraryStatus Enum
public enum LibraryStatus
{
Watching,
Completed,
[EnumMember(Value = "On Hold")]
OnHold,
Dropped,
[EnumMember(Value = "Plan To Watch")]
PlanToWatch
}
Class
public class LibraryListing
{
...
[JsonConverter(typeof(StringEnumConverter))]
public LibraryStatus LibraryStatus { get; set; }
...
}
When I pass the Model to view:
var initialData = @Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
JSON Output
[{"AnimeListId":2146,"LibraryStatus":"On Hold","AnimeAccountId":3},{"AnimeListId":2165,"LibraryStatus":"Plan To Watch","AnimeAccountId":3},{"AnimeListId":2145,"LibraryStatus":"Watching","AnimeAccountId":3},{"AnimeListId":2174,"LibraryStatus":"On Hold","AnimeAccountId":3},{"AnimeListId":2143,"LibraryStatus":"Watching","AnimeAccountId":3},{"AnimeListId":2171,"LibraryStatus":"Dropped","AnimeAccountId":3}]
Look at the "LibraryStatus" key, it has a value of "On Hold"
However, when I do a call like this:
var output = Enum.GetValues(typeof(LibraryStatus));
the output is:
[0] => "Watching",
[1] => "Completed",
[2] => "OnHold", *****
[3] => "Dropped",
[4] => "PlanToWatch" *****
I basically need the enum names statically. How can I get the output to match? Or better yet, anyone have a better method/suggestions? I basically need the output so I can filter the data on the view.
Upvotes: 2
Views: 115
Reputation: 27367
Try this:
private List<String> GetEnumNames(Type enumType)
{
return enumType.GetMembers(BindingFlags.Public | BindingFlags.Static).Select(m => {
var attr = m.GetCustomAttribute<EnumMemberAttribute>();
if (attr != null)
return attr.Value;
return m.Name;
}).ToList();
}
Running:
var output = GetEnumNames(typeof(LibraryStatus));
output.Dump();
Gives me the output:
Watching
Completed
On Hold
Dropped
Plan To Watch
Upvotes: 3