Chartjs-Implementing bar chart in .NET -6 Razor Pages using Chart.js plugin

1👍

but it is not able to assign into variable ‘data:data.datasets’

Error is here:

datasets: [{
            label: legendTitle,
            data:data.datasets,
            borderWidth: 1,                                                        
          }]

Single dataset in chartjs is complex object with data points and options.
So, in sample provided you are trying to pass to data points property (array of primitive integer values) the bunch of datasets.

Quick fix:

data: {
       labels:data.labels,
       datasets: [...data.datasets]                           
       }

Changed colors and scrapped data from here.

Displaying TOP-10 countries:

public JsonResult OnGetBarChart()
{
    var vm = new ChartVM();
    vm.Datasets = new List<DataSetRow>();

    var result = context.Populations.OrderByDescending(x => x.TotalPop).Take(10).ToList();
    vm.Labels = result.Select(x => x.Name).ToList();

    var ds1 = new DataSetRow
    {
        Label = "Male",
        BackgroundColor = "#ffA500",
        BorderColor = "#ffA500",
        Data = result.Select(x => x.MalePop).ToList()
    };
    var ds2 = new DataSetRow
    {
        Label = "Female",
        BackgroundColor = "#00B612",
        BorderColor = "#00B612",
        Data = result.Select(x => x.FemalePop).ToList()
    };
    vm.Datasets.Add(ds1);
    vm.Datasets.Add(ds2);

    return new JsonResult(vm);
}

TOP10

Leave a comment