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?
You could try this:
If the keys are still of type
MyEnumthen they should automatically be expressed as the names of the enum values.If that doesn't work, you could also try this:
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
MyEnumvalues (say, if you defined values 1-4 and the key was 17) you'll still get the key value as a numeric string.