0

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?

TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96

1 Answers1

1

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);
levent
  • 3,464
  • 1
  • 12
  • 22