Chartjs-How to create a charts in Razor Pages pulling data from the database?

1👍

Here is a working demo you could follow:

Model:

public class Revenue
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public string Month { get; set; }
}
public class Expense
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public string Month { get; set; }
}

Page:

@page
@model IndexModel

<canvas id="Chart1" width="500" height="300"></canvas>
   
@section Scripts
{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js" integrity="sha256-qSIshlknROr4J8GMHRlW3fGKrPki733tLq+qeMCR05Q=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js" integrity="sha256-xKeoJ50pzbUGkpQxDYHD7o7hxe0LaOGeguUidbq6vis=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css" integrity="sha256-IvM9nJf/b5l2RoebiFno92E5ONttVyaEEsdemDC6iQA=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js" integrity="sha256-arMsf+3JJK2LoTGqxfnuJPFTU4hAK57MtIPdFpiHXOU=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                type: "Get",
                url: "/?handler=RevenueData",   
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    console.log(response.revenue);
                    console.log(response.revenue.length);
                    var data = response.revenue;
                    var data2 = response.expense;
                    var labels = response.month;
                    var color1 = [];
                    var color2 = [];
                    for (var i = 0; i < response.month.length; i++)
                    {
                        color1.push("rgba(255, 99, 132, 0.2)");
                        color2.push("rgba(54, 162, 235, 0.2)");
                    }
  
                    var ctx = document.getElementById("Chart1");
                    var myChart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [{
                                label: 'Revenue',
                                data: data,
                                backgroundColor: color1,
                            },
                            {
                                label: 'Expense',
                                data: data2,
                                backgroundColor: color2
                            }]
                        },
                        options: {
                            responsive: false,
                            scales: {
                                xAxes: [{
                                    ticks: {
                                        maxRotation: 90,
                                        minRotation: 80
                                    },
                                    gridLines: {
                                        offsetGridLines: true 
                                    }
                                },
                                {
                                    position: "top",
                                    ticks: {
                                        maxRotation: 90,
                                        minRotation: 80
                                    },
                                    gridLines: {
                                        offsetGridLines: true 
                                    }
                                }],
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                    }
                                }]
                            }
                        }
                    });
                  
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    </script>
}

Handler:

public class IndexModel : PageModel
{
    private readonly YourDbContext _context;

    public IndexModel(YourDbContext context)
    {
        _context = context;
    }
    public void OnGet()
    {

    }
    public JsonResult OnGetRevenueData()
    {
        var countRevenue = (from t in _context.Revenue
                           group t by new
                           {
                               Month = t.Month
                           } into g
                           select  g.Sum(a=>a.Amount)
                           ).ToArray();
        var countExpense = (from t in _context.Expense
                            group t by new
                            {
                                Month = t.Month
                            } into g
                            select g.Sum(a => a.Amount)
                           ).ToArray();
        var monthList = _context.Revenue.Select(a => a.Month).Distinct().ToArray();
        return new JsonResult(new { revenue = countRevenue, expense = countExpense, month = monthList });
    }
}

Leave a comment