Search code examples
arraysjsonasp.net-mvctranslatejsonresult

How can I return a Dictionary<string, Object> as JsonResult, AND get the proper result in JavaScript?


I'm constructing my JsonResult in Controller by adding some extra information to an already existing JsonResult (returned from a different method). In order to add more properties, I converted the initial JsonResult into a Dictionary:

IDictionary<string, object> wrapper = (IDictionary<string, object>)new 
     System.Web.Routing.RouteValueDictionary(json.Data);

Then I just add data by writing wrapper["..."] = "value".

The method returns a new JsonResult, with wrapper as .Data:

new JsonResult() { wrapper, JsonRequestBehavior.AllowGet };

and that's where the troubles start; while communication happens perfectly, and the success function gets called, the resulting array which I use in JavaScript doesn't have the clean structure I expect: instead of accessing values as val = ret.PropName1; I end up having to access a simple indexed array, which contains in turn a dictionary with two pairs: { "Value"="val, "Key"="PropName1" }; (so something like o[0].Key would give me the property name)

I'd like to know if there's a smart, fast way to rewrite the JsonResult creation in the Controller, to get a nice clean dictionary in the View. There are a couple of ideas I have, but they aren't particularly clean: I could throw away JsonResult reuse on the server side, and just make an anonymous object with all the right properties; or, I could make a translation function in Javascript which could translate the result into a new Array(). I'm looking for better solutions.

[Later Edit] The array comes the way it does because the dictionary was defined as <string, object>. If it were <string, string>, it would be sent the way I'd originally expect it. But since I actually use objects from that bag, I'll just leave it the way it is, and pass the json response through the below function.


Solution

  • Addendum: while writing the above question, it occurred to me that the translation between 'bad' array and 'good' array is indeed very simple:

        function translateAjaxResult(ret) {
            var result = new Array();
    
            if (ret == null) return result;
            for(var i = 0; i < ret.length; i++)
                result[ret[i].Key] = ret[i].Value;
            return result;
        }
    

    Nonetheless, it's still a patch to a problem and not a fix to a problem, so I'd still like a more elegant solution.