DEV Community

Discussion on: ChartJS Tutorial With ASP.NET Core 2.2 Razor Pages

Collapse
 
micmuller profile image
Michael Müller

Hi Zoltan , thanks a lot for the tutorial, I learned a lot and try to implement ChartJS into my Razor Page Model Project. I'm struggling right now in the adaption from synchronious method to async. (in "public JsonResult OnGetInvoiceChartData() " ). I use SQL as a Database for my data and therefore use async method to access the data. Can you give me a hint how to change the following Method in Index.cshtml.cs

public JsonResult OnGetInvoiceChartData()
{
InvoiceList = _invoiceService.GetInvoices();
var invoiceChart = new CategoryChartModel();
invoiceChart.AmountList = new List();
invoiceChart.CategoryList = new List();

        foreach (var inv in InvoiceList)
        {
            invoiceChart.AmountList.Add(inv.Amount);
            invoiceChart.CategoryList.Add(inv.CostCategory);                
        }

return new JsonResult(invoiceChart);
}

into a working async method? Or an example or a adapted chartjs tutorial with database access :-) ? Any help would be very helpfull!
Thanks a lot
Michael

Collapse
 
zoltanhalasz profile image
Zoltan Halasz

Hi! Code below updated
Let's say you have an async method to obtain a list of invoices:

 public async Task<JsonResult> OnGetInvoiceChartData()
        {
            InvoiceList = await _invoiceService.GetInvoicesAsync();
            var invoiceChart = new CategoryChartModel();
            invoiceChart.AmountList = new List<double>();
            invoiceChart.CategoryList = new List<string>();

            foreach (var inv in InvoiceList)
            {
                invoiceChart.AmountList.Add(inv.Amount);
                invoiceChart.CategoryList.Add(inv.CostCategory);                
            }

            return new JsonResult(invoiceChart);
        }
Collapse
 
micmuller profile image
Michael Müller

Great, it works now!!! I did it in the same way in the past, but you made me confident, that it should work. So I started a brand new Project with a simple database and your Data. I had 2 issues in my code.

1) with .Net Core 3.1 Framework, which I used, you have to add the Nuget Package "Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.0" and add "services.AddMvc().AddNewtonsoftJson();" in Startup.cs under ConfigureServices. I found this solution somewhere in the net.
2) I used OnGetInvoiceChartDataAsync in "public async Task OnGetInvoiceChartDataAsync()" and it seems that JsonResult doesn't allow the Async word at the end... It just dropes the output, no Error, nothing ..

Anyway, thank you very much for your help and for the tutorial... It helped me lot!

Michael

Thread Thread
 
zoltanhalasz profile image
Zoltan Halasz

Glad that I could help.