Search code examples
c#ajaxasp.net-corecanvasjsjsonresult

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


I am using Canvasjs to develop charts inside a .NET Core 3.1 Razor Page Application. I need the chart to render on the Razor Page after an AJAX call which then returns Json data.

I've been using this as an example https://canvasjs.com/asp-net-mvc-charts/json-data-api-ajax-chart/ although it is for ASP.NET MVC.

This is my code.

Razor Page (Ajax Call)

Calls a method in Page Model called ChartData with a return type of Jsonresult. I then loop through the returned data and assign it to an array variable called dataPoints, and this is then provided to the chart, and then rendered.

$.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>

Page Model

//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));
    }

When this code executes, I don't get any errors within my IDE (Visual Studio 2019) or Developer Tools within my Web Browser (Chrome). But my chart doesn't load any of the data either.

enter image description here

I

I'd really appreciate any guidance and if you need further information or code, please just ask :)

Thanks.


Solution

  • The response that you are getting from ajax request is of type string and not in JSON format. You can parse the response data like data = JSON.parse(data); before passing it to dataPoint.