使用Flot chart js和Controller中的数据渲染图表

时间:2017-04-20 08:39:37

标签: c# json ajax asp.net-mvc flot

我正在尝试使用Flot Chart JS渲染条形图。数据根据数据库动态变化。调试时,数据不会被渲染出来。我尝试在行中断点(var data = strdata;)以找出我的数据发生了什么。最终数据仅包含一组数据值,例如“[0,5]”。看起来字符串无法加入foreach循环。

更新:好的。我知道字符串不能在循环中连接。我已经编辑了动作代码并将我的上一行放在评论中。数据和刻度的内容是正确的,但图表仍然没有数据。

控制器:

string strdata;
string strtick;
[HttpGet]
public ActionResult GetTestData()
    {
        string name;
        int count;

        int i = 0;

        var list1 = dbContext.Collections.ToList();
        foreach (Collection coll in list1)
        {

            name = coll.Name.ToString();
            var list2 = dbContext.Item.Where(x => x.Name == name).ToList();
            count = list2.Count();
            displaydata = "[" + i + "," + collcount + "],";
            displaytick = "[" + i + "," + collname + "],";
            strdata += displaydata;
            strtick += displaytick;
            //strdata = string.Join(",", "[" + i + "," + count + "]");
            //strtick = string.Join(",", "["+ i + "," +name+"]");
            //i++;
        }

        var data = strdata;
        var ticks = strtick;
        var result = new {data = data, ticks = ticks };
        return Json(result, JsonRequestBehavior.AllowGet);
    } 

查看:

$.ajax({
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: '/Home/GetTestData/',
        error: function () {
            alert("An error occurred.");
        },
        success: function (data) {
            //alert("Success.");

            var dataset = [{ label: "2012 Average Temperature", data: [data.data], color: "#5482FF" }];
            var ticks = [data.ticks];

            var options = {
                series: {
                    bars: {
                        show: true
                    }
                },
                bars: {
                    align: "center",
                    barWidth: 0.5
                },
                xaxis: {
                    axisLabel: "World Cities",
                    axisLabelUseCanvas: true,
                    axisLabelFontSizePixels: 12,
                    axisLabelFontFamily: 'Verdana, Arial',
                    axisLabelPadding: 10,
                    ticks: ticks
                },

                legend: {
                    noColumns: 0,
                    labelBoxBorderColor: "#000000",
                    position: "nw"
                },
                grid: {
                    hoverable: true,
                    borderWidth: 2,
                    backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
                }
            };

            $.plot($("#flot-dashboard5-chart"), dataset, options);
        }
    });

0 个答案:

没有答案