Jared
Jared

Reputation: 416

chart js, loading data dynamically

I'm attempting to load data from my ViewModel into Chart Js. It appears I am close, but possibly my javascript syntax is a bit off.

My model contains a list of integers. Currently, hard coded to three different ints. Has anyone done something similar to what I am looking to achieve?

Here is my view:

@model CRADV.ViewModel.RejectMessageReportViewModel

@{
    List<int> data = Model.reject_count;
    var labels = Model.messages;
    var colors = new[] {  "#FF6384", "#36A2EB", "#FFCE56" };
}
<div class="col-lg-4">
    <canvas id="pie-chart" width="400" height="400"></canvas>

    @Model.reject_count.FirstOrDefault()
</div>
<script type="text/javascript">
    var data = '@data.ToList()';
    var ctx = document.getElementById("pie-chart");
    var myPieChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: [
                        "#FF6384",
                        "#36A2EB",
                        "#FFCE56"
            ],
            datasets: [
                {
                    data: data,
                    backgroundColor: [
                        "#FF6384",
                        "#36A2EB",
                        "#FFCE56"
                    ],
                    hoverBackgroundColor: [
                        "#FF6384",
                        "#36A2EB",
                        "#FFCE56"
                    ]
                }]
        }
    });
</script>

Upvotes: 0

Views: 685

Answers (1)

Vax
Vax

Reputation: 353

It looks like you are trying to assign .NET list of integers to a jQuery function. This is never going to work as you are mixing two languages. You need to serialize List to JSON first.

You can achieve this using Newtonsoft Json nuget package:

using Newtonsoft.Json;

var data= JsonConvert.SerializeObject(Model.reject_count);

Upvotes: 1

Related Questions