Canvasjs 图表不会在 Razor 页面中使用 Jsonresult 数据呈现

Canvasjs Chart won't render using Jsonresult data in Razor Pages

我正在使用 Canvasjs 在 .NET Core 3.1 Razor 页面应用程序中开发图表。我需要在 AJAX 调用之后在 Razor 页面上呈现图表,然后 returns Json 数据。

我一直在用它作为示例 https://canvasjs.com/asp-net-mvc-charts/json-data-api-ajax-chart/ 尽管它适用于 ASP.NET MVC。

这是我的代码。

剃刀页面(Ajax调用)

调用页面模型中名为 ChartData 的方法,return 类型为 Jsonresult。然后我遍历 returned 数据并将其分配给一个名为 dataPoints 的 array 变量,然后将其提供给图表,然后进行渲染。

$.ajax({
          method: 'get',
          url: '/SPC/Index2?handler=ChartData',
          contentType: "application/json",
          dataType: "json",
                success: function (data) {
                    //alert(JSON.stringify(data));
                    //alert(data);

                    var dataPoints = [];
                    var chart

                    for (var i = 0; i < data.length; i++) {
                        dataPoints.push({
                            x: new Date(data[i].x),
                            y: data[i].y
                        });

                        chart = new CanvasJS.Chart("chartContainer", {
                            animationEnabled: true,
                            title: {
                                text: "My Test Chart"
                            },
                            axisX: {
                                valueFormatString: "DD MMM"
                            },
                            axisY: {
                                title: "Sales (in USD)",
                                prefix: "$"
                            },
                            data: [{
                                type: "spline",
                                xValueType: "dateTime",
                                xValueFormatString: "DD MMM",
                                yValueFormatString: "$#,###",
                                dataPoints: dataPoints
                                //dataPoints: [{ "x": 1637597471269.0, "y": 2500.0 }, { "x": 1637683871269.0, "y": 2600.0 }, { "x": 1637770271269.0, "y": 2700.0 }]
                            }]
                        });

                        chart.render();

            }
            }
           });

<div id="chartContainer" style="height: 370px; width: 100%;"> 
</div>

页面模型

//DataContract for Serializing Data - required to serve in JSON format
[DataContract]
public class DataPoint
{
    public DataPoint(double x, double y)
    {
        this.x = x;
        this.y = y;
    }

    //Explicitly setting the name to be used while serializing to JSON.
    [DataMember(Name = "x")]
    public Nullable<double> x = null;

    //Explicitly setting the name to be used while serializing to JSON.
    [DataMember(Name = "y")]
    public Nullable<double> y = null;
}

public JsonResult OnGetChartData()
    {
        var converted = DateTime.Now.ToOADate();

        DateTime one = DateTime.Now;
        DateTime two = DateTime.Now.AddDays(1);
        DateTime three = DateTime.Now.AddDays(2);

        DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        var c_one = (long)(one - sTime).TotalMilliseconds;
        var c_two = (long)(two - sTime).TotalMilliseconds;
        var c_three = (long)(three - sTime).TotalMilliseconds;

        dataPoints = new List<DataPoint>();

        dataPoints.Add(new DataPoint(c_one, 2500));
        dataPoints.Add(new DataPoint(c_two, 2600));
        dataPoints.Add(new DataPoint(c_three, 2700));

        JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };

        return new JsonResult(JsonConvert.SerializeObject(dataPoints, _jsonSetting));
    }

执行此代码时,我的 IDE(Visual Studio 2019)或网络浏览器(Chrome)中的开发人员工具没有出现任何错误。但是我的图表也没有加载任何数据。

非常感谢任何指导,如果您需要更多信息或代码,请直接询问 :)

谢谢。

你检查一下你View的顺序是否正确。我改了之后就可以显示数据了。我还是以官方数据为例,像这样:

查看:

@{
    Layout = null;
}

<!DOCTYPE HTML>
<html>
<head>
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
    <script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>

</head>
<body>

    <div id="chartContainer" style="height: 370px; width: 100%;"></div>
</body>


</html>

<script>
    $.ajax({
        method: 'get',
        url: '/test/json',
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            //alert(JSON.stringify(data));
            //alert(data);

            var dataPoints = [];
            var chart

            for (var i = 0; i < data.length; i++) {
                dataPoints.push({
                    x: new Date(data[i].x),
                    y: data[i].y
                });

                chart = new CanvasJS.Chart("chartContainer", {
                    animationEnabled: true,
                    title: {
                        text: "My Test Chart"
                    },
                    axisX: {
                        valueFormatString: "DD MMM"
                    },
                    axisY: {
                        title: "Sales (in USD)",
                        prefix: "$"
                    },
                    data: [{
                        type: "spline",
                        xValueType: "dateTime",
                        xValueFormatString: "DD MMM",
                        yValueFormatString: "$#,###",
                        dataPoints: dataPoints
                        //dataPoints: [{ "x": 1637597471269.0, "y": 2500.0 }, { "x": 1637683871269.0, "y": 2600.0 }, { "x": 1637770271269.0, "y": 2700.0 }]
                    }]
                });

                chart.render();

            }
        }
    });

</script>

控制器:

 public IActionResult Index()
        {
            return View();
        }

        public ContentResult JSON()
        {
            List<DataPoint> dataPoints = new List<DataPoint>();


            dataPoints.Add(new DataPoint(1481999400000, 4.67));
            dataPoints.Add(new DataPoint(1482604200000, 4.7));
            dataPoints.Add(new DataPoint(1483209000000, 4.96));
            dataPoints.Add(new DataPoint(1483813800000, 5.12));
            dataPoints.Add(new DataPoint(1484418600000, 5.08));
            dataPoints.Add(new DataPoint(1485023400000, 5.11));
            dataPoints.Add(new DataPoint(1485628200000, 5));
            dataPoints.Add(new DataPoint(1486233000000, 5.2));
            dataPoints.Add(new DataPoint(1486837800000, 4.7));
            dataPoints.Add(new DataPoint(1487442600000, 4.74));
            dataPoints.Add(new DataPoint(1488047400000, 4.67));
            dataPoints.Add(new DataPoint(1488652200000, 4.66));
            dataPoints.Add(new DataPoint(1489257000000, 4.86));
            dataPoints.Add(new DataPoint(1489861800000, 4.91));
            dataPoints.Add(new DataPoint(1490466600000, 5.12));
            dataPoints.Add(new DataPoint(1491071400000, 5.4));
            dataPoints.Add(new DataPoint(1491676200000, 5.08));
            dataPoints.Add(new DataPoint(1492281000000, 5.05));
            dataPoints.Add(new DataPoint(1492885800000, 4.98));
            dataPoints.Add(new DataPoint(1493490600000, 4.89));
            dataPoints.Add(new DataPoint(1494095400000, 4.9));
            dataPoints.Add(new DataPoint(1494700200000, 4.95));
            dataPoints.Add(new DataPoint(1495305000000, 4.88));
            dataPoints.Add(new DataPoint(1495909800000, 5.07));
            dataPoints.Add(new DataPoint(1496514600000, 5.14));
            dataPoints.Add(new DataPoint(1497119400000, 5.05));
            dataPoints.Add(new DataPoint(1497724200000, 5.03));
            dataPoints.Add(new DataPoint(1498329000000, 4.93));
            dataPoints.Add(new DataPoint(1498933800000, 4.97));
            dataPoints.Add(new DataPoint(1499538600000, 4.86));
            dataPoints.Add(new DataPoint(1500143400000, 4.95));
            dataPoints.Add(new DataPoint(1500748200000, 4.83));
            dataPoints.Add(new DataPoint(1501353000000, 4.83));
            dataPoints.Add(new DataPoint(1501957800000, 4.73));
            dataPoints.Add(new DataPoint(1502562600000, 4.56));
            dataPoints.Add(new DataPoint(1503167400000, 4.34));
            dataPoints.Add(new DataPoint(1503772200000, 4.25));
            dataPoints.Add(new DataPoint(1504377000000, 4.18));
            dataPoints.Add(new DataPoint(1504981800000, 4.22));
            dataPoints.Add(new DataPoint(1505586600000, 4.18));
            dataPoints.Add(new DataPoint(1506191400000, 4.31));
            dataPoints.Add(new DataPoint(1506796200000, 4.34));
            dataPoints.Add(new DataPoint(1507401000000, 4.47));
            dataPoints.Add(new DataPoint(1508005800000, 4.57));
            dataPoints.Add(new DataPoint(1508610600000, 4.63));
            dataPoints.Add(new DataPoint(1509215400000, 4.55));
            dataPoints.Add(new DataPoint(1509820200000, 4.55));
            dataPoints.Add(new DataPoint(1510425000000, 4.44));
            dataPoints.Add(new DataPoint(1511029800000, 4.46));
            dataPoints.Add(new DataPoint(1511634600000, 4.41));
            dataPoints.Add(new DataPoint(1512239400000, 4.3));
            dataPoints.Add(new DataPoint(1512844200000, 4.31));
            dataPoints.Add(new DataPoint(1513449000000, 4.3));
            dataPoints.Add(new DataPoint(1513621800000, 4.36));


            JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
            return Content(JsonConvert.SerializeObject(dataPoints, _jsonSetting), "application/json");
        }
    }

型号:

 [DataContract]  
    public class DataPoint
    {
        public DataPoint(double x, double y)
        {
            this.X = x;
            this.Y = y;
        }

        //Explicitly setting the name to be used while serializing to JSON.
        [DataMember(Name = "x")]
        public Nullable<double> X = null;

        //Explicitly setting the name to be used while serializing to JSON.
        [DataMember(Name = "y")]
        public Nullable<double> Y = null;
    }

结果:

您从 ajax 请求获得的响应是​​字符串类型,而不是 JSON 格式。在将响应数据传递给 dataPoint 之前,您可以像 data = JSON.parse(data); 一样解析响应数据。