Hello Team,
Help me bind sales data to my line graph
// This is to get sales performance by Month on the Line Graph and the chart area
public JsonResult GetSalesPerformanceOnGraph()
{
ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities();
var previousYear = (DateTime.Now.Year - 1);
var sales = db.tblSales.ToList();
var salesByMonthAmount = (from a in sales
where DateTime.Parse(a.OrderDate).Year > previousYear
group a by DateTime.Parse(a.OrderDate).Month into g
select g.Sum(c => c.TotalAmount)).ToArray();
var salesMonths = (from a in sales
where DateTime.Parse(a.OrderDate).Year >
).ToList();
return Json(new , JsonRequestBehavior.AllowGet);
}

Vishal JoshiRank #377 · 6.7K reputationPosted Nov 21, 2023, 7:46 AM EST
Hello,
API Code looks good. you need to return data like the below code.
return Json(new { labels = salesMonths, values = salesByMonthAmount } , JsonRequestBehavior.AllowGet);You need to call API and bind data to the chart. please check out below code and add it to your respective chart.js file.
$.ajax({ type: "GET", url: "/controllerName/APINAme", cache: false, success: function(data){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets: [{ label: '# of Votes', data: data.values, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); } });Thanks
Vishal Joshi
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Nov 21, 2023, 10:21 AM EST
Thank you Mr Vishal, it is working