首页 > 解决方案 > 从 Razor 页面使用 JSON 更新 chart.js

问题描述

我的 Razor 页面中有一个 chart.js,其中显示了一些数据,但是当我尝试使用 AJAX 调用向图表添加附加数据集时,我收到一条错误消息:

Uncaught TypeError: Cannot create property 'data' on string '{"data":[{"x":"2020-01-11","y":12},{"x":"2020-01-12","y":100},{"x":"2020-01-13","y":2},{"x":"2020-01-14","y":122},{"x":"2020-01-16","y":20},{"x":"2020-01-19","y":2}],"label":"PRA Prime US100 M3","borderWidth":1,"borderColor":"rgba(255,99,132,1)","backgroundColor":"rgba(255,99,132,1)"}'

这是我的图表,可以很好地使用包含的数据集:

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'line',
    options: {
        responsive: true,
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    displayFormats: {
                        hour: 'YYYY-MM-DD HH:00:00',
                        day: 'YYYY-MM-DD',
                        week: 'YYYY-MM-DD',
                        month: 'MMM YYYY',
                        quarter: 'MMM YYYY'
                    }
                }
            }]
        }
    },
    data: {
        datasets: [
            {
                label: 'Test',
                data: [{
                    x: '2015-03-15',
                    y: 12
                },
                {
                    x: '2015-03-25',
                    y: 21
                },
                {
                    x: '2015-04-25',
                    y: 32
                },
                {
                    x: '2019-05-28',
                    y: 21
                }],
                borderWidth: 1,
                borderColor: 'rgba(255,99,132,1)',
                backgroundColor: 'rgba(255,99,132,1)',
            }]
    }
});

这是从 C# 代码中获取 JSON 格式的新数据集并尝试将其插入图表的 AJAX 函数:

function algoCBChecked(checkbox) {
    var sName = checkbox.id;

    var run = $.ajax({
        type: 'GET',
        data: { sName: sName },
        dataType: 'json',
        contentType: 'application/json',
        url: '/index?handler=AlgoCBChecked',
        success: function (res) {
            addDataToChart(res);
        },
        error: function (xhr, status, errorThrown) {
            alert("An error occered, " + errorThrown);
        }
    });
}

function addDataToChart(data) {
    myChart.data.datasets.push(data);
    myChart.update();
}

这是从 AJAX 调用并以 JSon 格式返回新数据集的 C# 代码:

public IActionResult OnGetAlgoCBChecked(string sName)
        {
            chartDataset ds = new chartDataset();
            ds.label = sName;
            ds.borderWidth = 1;
            ds.borderColor = "rgba(255,99,132,1)";
            ds.backgroundColor= "rgba(255,99,132,1)";
            ds.data.Add(new chartData { x = "2020-01-11", y = 12 });
            ds.data.Add(new chartData { x = "2020-01-12", y = 100 });
            ds.data.Add(new chartData { x = "2020-01-13", y = 2 });
            ds.data.Add(new chartData { x = "2020-01-14", y = 122 });
            ds.data.Add(new chartData { x = "2020-01-16", y = 20 });
            ds.data.Add(new chartData { x = "2020-01-19", y = 2 });

            string json = JsonConvert.SerializeObject(ds);

            return new JsonResult(json);
        }

最后是 chartDataset 和 chartData 类:

public class chartData
    {
        public string x { get; set; }
        public int y { get; set; }
    }

    public class chartDataset
    {
        public string label { get; set; }
        public List<chartData> data = new List<chartData>();
        public int borderWidth { get; set; }
        public string borderColor { get; set; }
        public string backgroundColor { get; set; }
    }

我可以看到 JSON 已传递给 addDataToChart 函数,但无法添加到图表中。我的 JSON 格式是否错误?

标签: c#json.netchart.js

解决方案


JsonResult “将给定的结果格式化为 JSON。”

通过给它一个 JSON 字符串,你最终会向浏览器发送一个双序列化的值。所以即使在 jQuery 反序列化它之后,你仍然会得到一个字符串而不是一个对象。

因此,与其传递JsonResult序列化的字符串表示,不如给它你想要序列化的对象。

return new JsonResult(ds);

推荐阅读