4

When I make an ajax call from javascript to a controller the string value is converted correctly and automatically for me to the enum field with the same name.
However, going the other way, returning Json() from a controller, has the enum field send it's numeric value instead of it's string representation.

How can I get the string representation to get back to javascript without invading the serializer all that much. Below is what I currently have and I thought it would work, but it's not. I'm still getting 0 or 1 returned from the ajax call.

 [DataContract]
 public enum Uom
 {
     [EnumMember(Value="CD")]
     CD = 0,

     [EnumMember(Value="SD")]
     SD
 }
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
user441521
  • 6,942
  • 23
  • 88
  • 160
  • That accepted answer was in 2010. 4 years is a long time so I'm wondering if anything has changed in this besides messing around with the serilizer itself because if that's the case it's not even worth it in my case. I'll just convert it in javascript itself then, but if it's some annotation or whatever to make this work then it's worth it. – user441521 Jul 17 '14 at 15:23
  • 1
    I wish I was joking, but it still applies. The `Json()` result uses the built in .NET JSON seralizer by default, and it's still serializing enum's to strings. You could switch to JSON.NET without too much trouble if you wanted. – Steven V Jul 17 '14 at 15:28
  • Bummer. OK, thanks. I'll just manually convert on the javascript side. – user441521 Jul 17 '14 at 15:31

1 Answers1

2

in the webapiconfig.cs

add the following

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
                (new Newtonsoft.Json.Converters.StringEnumConverter());

this will change all the enum to strings. hope this helps.

Anto Subash
  • 3,140
  • 2
  • 22
  • 30