我正在尝试使用JsonResult
和Chart.js
这是我正在尝试的代码
$.ajax({
type: "POST",
url: "/User/Pie/",
data: { 'campaignID': 5 },
success: function (data) {
pieData = data;
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
},
error: function (data) {
alert("Error:" + JSON.stringify(data));
}
});
控制器
[HttpPost]
public JsonResult Pie(string campaignID)
{
try
{
return Json("[{ value: 40, color: \"#000000\"},{value: 60,color: \"#01dfde\"},{value: 60,color: \"#01dfde\"}]", JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return null;
}
}
哪个不行。我成功从控制器获取Json,但图表不可见。
如果我静态地将Json放在pieData中,那么它的工作正常
pieData = [{ value: 40, color: \"#000000\"},{value: 60,color: \"#01dfde\"},{value: 60,color: \"#01dfde\"}];
我也试过Json.Parse
答案 0 :(得分:1)
您应该将c#数组传递给Json
方法,它会将其转换为json本身:
var pieData= new[]
{
new { value = 40, color = "#000000" },
new { value = 60, color="#01dfde"},
new { value=60, color = "#01dfde"}
};
return Json(pieData, JsonRequestBehavior.AllowGet);