Render Dictionary Enum keys as named values

331 Views Asked by At

I have an Enum looking something like this:

public Enum MyEnum {EnumA = 0, EnumB = 10, EnumC = 20}

I also have a Dictionary model that I wish to use in my Razor view in which I would like to assign the keys of the Dictionary to a javascript array like this:

var myArray = @Html.Raw(Json.Encode(Model.Keys.ToArray()))

This results in myArray = [0,10,20] which is pretty close to what I want. I would like the "text" value of the enum to be added instead of the numerical values, like this: myArray = ["EnumA","EnumB","EnumC"]

When displaying a single enum field @Html.DisplayFor can be used to convert the numerical value to the enum "text" value.

Is there a way to have my keys converted in the same way without having to loop through them and add them to the array manually?

2

There are 2 best solutions below

3
Ann L. On BEST ANSWER

You could try this:

var values = Model.Keys.ToArray().Select(val => val.ToString());
var myArray = @Html.Raw(Json.Encode(values));

If the keys are still of type MyEnum then they should automatically be expressed as the names of the enum values.

If that doesn't work, you could also try this:

var values = Model.Keys.ToArray().Select(val => ((MyEnum)val).ToString());
var myArray = @Html.Raw(Json.Encode(values));

This assumes that if your keys aren't still of type MyEnum, they are at least integers.

Be aware that if the values in the keys don't correspond to defined MyEnum values (say, if you defined values 1-4 and the key was 17) you'll still get the key value as a numeric string.

2
Emre Kabaoglu On

You could use Enum.Parse;

var array = new List<int> {0, 10, 20};
var arrayEnum = array.Select(x => Enum.Parse(typeof(MyEnum), x.ToString())).ToList();