Search code examples
chart.js.net-6.0razor-pages

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


  • chart is displaying but vertical bar is not showing. data is coming from handler but it is not able to assign into variable 'data:data.datasets'. Please help me.*

Model Class

ChartVM.cs
*use for definig the properties for chart displaying *

public class ChartVM
{
   public List<string> Labels{get;set;}
   public List<DataSetRow> Datasets{get;set;}
        
}
public class DataSetRow
{
   public List<int> Data{get;set;}
   public string BackgroundColor { get;set;}
   public string Color { get; set; }
}

ChartDemo.cs

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

            var result = context.CountryPopulations.ToList();
            vm.Labels = result.Select(x => x.Name).ToList();

            var ds1 = new DataSetRow
            {
                BackgroundColor = "#f2f2f2",
                Color = "#24248f",
                Data = result.Select(x => x.Male).ToList()
            };
            var ds2 = new DataSetRow
            {
                BackgroundColor = "#f2f2f2",
                Color = "#ff0080",
                Data = result.Select(x => x.Female).ToList()
            };
            vm.Datasets.Add(ds1);
            vm.Datasets.Add(ds2);
            return new JsonResult(vm);

     }

ChartDemo.cshtml

HTML code

   <div>
    <canvas id="myChart" style="max-height:400px; max-width:500px"></canvas>
</div>

javaScript

   <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/js/chart.min.js" asp-append-version="true"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            BarChart();
        });
        function BarChart() {
            var XaxisTitle = 'Colour Bar';
            var Yaxistitle = 'Rupees';
            var legendTitle = 'Months';
            const ctx = document.getElementById('myChart');
            debugger;
            $.ajax({
                type:'GET',
                url:'?handler=BarChart',
                data:{},
                success:function(data){
                    new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels:data.labels,
                            datasets: [{
                                label: legendTitle,
                                data:data.datasets,
                                borderWidth: 1,                                                        
                            }]
                        },
                        options: {
                            scales: {
                                x: {
                                    display: true,
                                    beginAtZero: true,
                                    title: {
                                        display: true,
                                        text: XaxisTitle,
                                        color: '#911',
                                        font: {
                                            family: 'Comic Sans MS',
                                            size: 20,
                                            weight: 'bold',
                                            lineHeight: 1.2,
                                        },
                                        padding: { top: 20, left: 0, right: 0, bottom: 0 }
                                    }
                                },

                                y: {
                                    display: true,
                                    title: {
                                        display: true,
                                        text: Yaxistitle,
                                        color: '#191',
                                        font: {
                                            family: 'Times',
                                            size: 20,
                                            style: 'normal',
                                            lineHeight: 1.2
                                        },
                                        padding: { top: 30, left: 0, right: 0, bottom: 0 }
                                    }
                                }
                            }
                        }
                    });
                },
                error:function(){
                    alert('Something went wrong!!');
                }
            });

            

        }
    </script>

see output image vertical bar is not showing enter image description here


Solution

  • 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