How to return a multidimensional array as JSON for jqPlot chart in ASP.NET MVC C#
The json needs to be in this format:
var data = [
['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],
['Out of home', 16],['Commuting', 7], ['Orientation', 9]
];
But in my action method I can't figure out how to construct the json to be rendered in that format. Here is what I have:
var json = new[] {
new[] {"Pending", summaryData.Sum(a => (int)a.Pending).ToString() },
new[] {"Completed", summaryData.Sum(a => (int)a.Completed).ToString()}
};
return Json(json, JsonRequestBehavior.AllowGet);
Which returns the following JSON:
[["Pending","146"],["Completed","914"]]
This is close except that their are quotes around the numeric values and jqPlot doesn't seem to like it. Unfortunately if I try to do a Int32.Parse(...) on it I get an exception开发者_JS百科.
Any ideas how to best do this?
Thanks
I'm guessing the error you get when you try to use Int32.parse
is something like "No best type found for implicitly-typed array." When using an implicitly typed array and the values in that array are of different types, the compiler doesn't know what type to infer for the array.
You can get around the error by telling the compiler a type for the arrays:
var json = new[] {
new object[] {"Pending", summaryData.Sum(a => (int)a.Pending) },
new object[] {"Completed", summaryData.Sum(a => (int)a.Completed) }
};
This should serialize the array the way you want it.
As for jqPlot, the quotes around the number are causing a problem because the plugin most likely required the second item in the array to be of type Number.
精彩评论