Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonResults returns Enum value instead of String representation

On my Client Side I have an ajax call like below:

          $.ajax({
                url: "Controller/ListResult",
                type: 'POST',
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify({
                    Id: ObjectId,
                    SessionKey: sessionManager.getSessionKey()
                }),
                dataType: "json",
                success: function (result) {
                var test = results;
                    }
                }
            });

In the Controller I have a method like this :

      [HttpPost]
       public JsonResult ListResult(string Id, string SessionKey)
       {
        IBl biz = new BL();
        var result = biz.GetResults(Id,SessionKey);
        return Json(result);
       }

The problem is the result that controller returns is an object which has Enum properties (with their string representation as value). However when it reaches the success function in the ajax call, the enums are no longer string representation, and instead, they have been converted to their int values. How can I avoid this? and keep the string representation on the javascript side.

like image 907
Benjamin Avatar asked Dec 24 '22 00:12

Benjamin


1 Answers

Instead of returning var result create some result entity class and you can mark the enum property there with StringEnumConverter.

class Result
{
  [JsonConverter(typeof(StringEnumConverter))]
  public EnumType EnumProperty { get; set; }

  *****other properties goes here****
}

As Stephen suggested this works if one is using Json.NET as the serializer.

like image 137
Navoneel Talukdar Avatar answered Feb 16 '23 03:02

Navoneel Talukdar