使用 Json 传递 Json 结果无法正常工作
Passing Json using JsonResult not working properly
我正在尝试使用 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
您应该将 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);
我正在尝试使用 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
您应该将 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);