Home > Blockchain >  Draw chart.js with data from server
Draw chart.js with data from server

Time:01-17

I know I must be doing a basic mistake but I am new to this. I would like to populate a line chart (chart.js) in my View with data from the server. I have confirmed that the data is received in the View but I suspect that it is in a wrong format.

My Controller:

public ActionResult GetLineChartData()
    {
        var data = new
        { 
            title = "test_data", 
            data = new[] {
                new { value = "V1", key = "11"},
                new{ value = "V2", key = "10"}
            }
        };
        return Json(data, JsonRequestBehavior.AllowGet);
    }

On my View:

<canvas id="lineChart" width="400" height="400"></canvas>
<button id="lineChartUpdate">Update Chart</button>
<script>
$(document).ready(function () {
    $("#lineChartUpdate").click(function () {
        $.ajax({
            type: "Post",
            url: '@Url.Action("GetLineChartData", "Posts")',
            data: {},
            dataType: "json",
            traditional: true,
            success: function (data) {
                new Chart('lineChart', {
                    type: 'line',
                    data: {
                        labels: data.data.map(a => a[0]),
                        datasets: [{
                            label: 'My Dataset',
                            data: data.data.map(a => a[1]),
                            fill: false,
                            borderColor: 'red'
                        }]
                    },
                    options: {
                        scales: {yAxes: [{ ticks: { beginAtZero: true } }]}
                    }
                });
            }
        });
    });
});
</script>

I am getting this error: "Invalid scale configuration for scale: yAxes"

CodePudding user response:

This is because it is invalid as the errors says, you are using V2 config with V3.

In V3 all scales are there own object in the scales object instead of 2 arrays.

Changing to:

scales: {
  y: {
     // Scale config
   }
}

Will remove the warning and make the config apply correctly

For all changes between V2 and V3 please read the migration guide

  •  Tags:  
  • Related