sorry for the dummy question but I cannot find a simple and clean way for doing something as simple as that. I have an MVC controller which should return a JSON object to be consumed by some JavaScript; if I set its return type to JsonResult and return Json(objecttoserialize) I can see through Firebug that the JSON code is returned and interpreted correctly. Anyway, I have to use a manually encoded JSON string because:
- the component which serializes the object I want to return is hosted
in an external library and I should not touch it. - this component serializes on its own because it has a Dictionary
member representing the property NAME and VALUE of the corresponding JS object.
For instance, an entry in the dictionary like “width” for the key and “20” for the value must be serialized as { width: “20” }, i.e. as if the .NET object had a property Width with value 20, whereas it simply has a dictionary with a variable number of such property/value pairs to be represented by object properties in JS objects. This is why the component has its own JSON serialization method. Thus, I should just return the JSON generated by it.
As the Json method serializes a .NET input object, I googled around I find I could rather use a ContentResult. Thus I tried by returning a ContentResult with Content=the serialized string and ContentType = “application/json”; anyway the JS client seems not able to understand this is a JSON object and fails. If instead I return a JsonResult it works as expected, but of course the properties represented by its Dictionary member are lost. I was expecting JsonResult to be equivalent to the ContentResult above, but this does not seem the case. The JS code is like:
request: function (nodeId, level, onComplete) {
$.ajax({
url: "/Node/Get", type: "POST", dataType: "json",
data: { id: nodeId, level: level, depth: 3 },
success: function (data) {
var ans = data;
onComplete.onComplete(nodeId, ans);
}
});
If I place a breakpoint in the script in Firebug, When I return JsonResult the success function is hit; when I return ContentResult, it is never hit and the page remains stuck loading the requested object. (This JS refers to the SpaceTree of http://www.thejit.org). Could anyone give a hint?
I managed to get it working with a sort of trick, but I’d like to know if there is a better solution for this, and at any rate if it is true that I really need to use JsonResult (or a derived class, like in this trick) to get JS work properly. I derived a class from JsonResult and changed the ExecuteResult method so that it just passes through the received JSON string: