使用JsonResult传递Json无法正常工作

时间:2015-03-26 11:59:23

标签: javascript json asp.net-mvc chart.js

我正在尝试使用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

1 个答案:

答案 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);