TyForHelpDude
TyForHelpDude

Reputation: 5002

how to convert Enum definition to JavaScript object (json)

I also checked this post but it gives me same result. enum definition:

    public enum myEnum
        {
            variable1 = 1,
            variable2 = 25,
            variable3 = 35
        }

Here's what I tried:

var myJsObject= @Html.Raw(JsonConvert.SerializeObject(Enum.GetValues(typeof(myEnum)), new Newtonsoft.Json.Converters.StringEnumConverter()));

and this is what it returns:

["variable1","variable2","variable3"]

Expected result:

{"1":"variable1","25":"variable2","35":"variable3",}

How can I achieve this?

Upvotes: 0

Views: 74

Answers (1)

levent
levent

Reputation: 3634

you can some thing like this..

   public enum myEnum
   {
      variable1 = 1,
      variable2 = 25,
      variable3 = 35
   }

    static Dictionary<int,string> EnumToDictionary<T>() where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an enum type");
        }
        var dictionary = Enum.GetValues(typeof(T))
            .Cast<T>()
            .ToDictionary( e=>  Convert.ToInt32(e), e => e.ToString());
        return dictionary;
    }

using...

var dictionary =  EnumToDictionary<tEnum>();
var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);

Upvotes: 1

Related Questions