Chartjs-Access data arrays from c# method inside JavaScript inside .cshtml file

1πŸ‘

but when I try to print out @Model.GetRandomData(6) it shows
β€œSystem.Int32[]”

You will get something like above mentioned when you try code like this.

var data = @Model.GetRandomData(6);

Razor is going to render the output like below if you check the view source of the page.

 var data = System.Int32[];

This happens because your GetRandomData method returns an int array and when razor is trying to execute your C# code, it is basically calling the ToString() which is returning the type.

If you want to get the array generated by your C# method to JavaScript array, you need to Serialize the output of the method.

The below should work.

var data = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.GetRandomData(6)));
let myChart = document.getElementById('myChart').getContext('2d');

let thisChart = new Chart(myChart, {
    type: 'bar', 
    data: {
        labels: ['1', '2', '3', '4', '5', '6'],
        datasets: [{
            label: 'test',
            data: data
        }]
    }
});

Leave a comment