简体   繁体   中英

Render Dictionary Enum keys as named values

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:

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM