Problem Defination :- We have a requirement in which we need to present Sales data of a company in different charts. So we have implemented Charts with Chart.JS a javascript library and fetch the Sales data from a table in database.You can better understand our requirement with below images.
Above image represents the table data into the database.It has three columns ID,MonthName and TotalSales of the respective Month.
Above image is the chart representation of the sales data in doughnut chart,you can change the chart type as shown in below image.
Implementation :- To implement charts functionality firstly we have to follow below steps
In The implemetation phase we will create one model class which is used for Sales Data.
Below is the code for Sales Model class.
public class Sales
{
[Key]
public int Id { get; set; }
public string MonthName { get; set; }
public int TotalSales { get; set; }
}
Now create a DBContext class and named it as demoDBcontext and add the public DbSet
Now Create the Controller with named Sales and write the below Action Methods into it.
ShowSalesData() is the method in which we are showing chart.
public IActionResult ShowSalesData()
{
return View();
}
[HttpPost]
public List<'object> GetSalesdata()
{
List<'object''> result = new List<'object''>();
List labels = _db.Salestable.Select(p => p.MonthName).ToList();
result.Add(labels);
List salesNumber = _db.Salestable.Select(p => p.TotalSales).ToList();
result.Add(salesNumber);
return result;
}
ShowSalesData View :- Design the view for presenting the chart and we create a button for show sales data when we click on this button charts will be appear in canvas.
For showing the data into the charts we have used a canvas and a dropdown list for chart type based on the selection of the chart type we present the data into the canvas using the Ajax call for controller and action method. Complete code for Javascript is shown in below image.
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.