How can I return the dictionary <string, Object> as JsonResult and get the correct result in JavaScript?

I create my JsonResult in the controller by adding additional information to an existing JsonResult (returned by another method). To add additional properties, I converted the original JsonResult to a dictionary:

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

Then I just add data, write wrapper["..."] = "value" .

The method returns a new JsonResult with a wrapper like .Data:

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

and that where trouble begins; while the connection is going fine and the success function is being called, the resulting array that I use in JavaScript does not have the clean structure that I expect: instead of accessing values ​​like val = ret.PropName1; I ultimately need to access a simple indexed array, which in turn contains a dictionary with two pairs: { "Value"="val, "Key"="PropName1" }; (so something like o[0].Key will give me the property name)

I would like to know if there is a smart, quick way to rewrite JsonResult creation in the controller in order to get a nice clean dictionary in the view. There are a few ideas that I have, but they are not particularly clean: I can throw away the reuse of JsonResult on the server side and just make an anonymous object with all the appropriate properties; or I could make a translation function in Javascript that could translate the result into a new array (). I am looking for the best solutions.

[Later Edit] . The array works like this because the dictionary was defined as <string, object> . If it were <string, string> , it would be sent as I expected. But since I actually use the objects from this bag, I just leave it as it is and pass the json response through the following function.

+4
source share
1 answer

Addendum: when writing the above question, it occurred to me that translating between a "bad" array and a "good" array is really 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; } 

However, it is still a patch for the problem, not a fix for the problem, so I will still like the more elegant solution.

+1
source

All Articles