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
 }
3
  • 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. Commented Jul 17, 2014 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. Commented Jul 17, 2014 at 15:28
  • Bummer. OK, thanks. I'll just manually convert on the javascript side. Commented Jul 17, 2014 at 15:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.