Skip to content

Charts in ASP.NET Core MVC

Problem definition: We need to present a company's sales data in different charts. So we implemented the charts with Chart.js, a JavaScript library, and fetched the sales data from a database table. The images below explain the requirement.

Monthly sales data table in the database

The image above shows the table data in the database. It has three columns: ID, MonthName and TotalSales for each month.

Sales data shown as a doughnut chart with Chart.js

The image above shows the sales data as a doughnut chart. You can change the chart type, as shown in the image below.

Changing the chart type from the dropdown list

Implementation: To implement the charts, follow the steps below.

  • Create a model class for the sales data.
  • Create a controller named Sales.
  • Add this Sales model class to the DbContext class and then run the migration commands.
  • Create an action method named ShowSalesData() to show the charts.
  • Create a method named GetSalesdata() to get the sales data from the database.
  • Create a view for the ShowSalesData() action method.
  • Add a reference to the Chart.js file from the official Chart.js website.

In the implementation phase, we create a model class for the sales data. Below is the code for the 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 named demoDBcontext and add the public DbSet Salestable { get; set; } DbSet to this class. It generates the table in the database when you run the migration commands.
Now create a controller named Sales and write the action methods below in it. ShowSalesData() shows the chart.

public IActionResult ShowSalesData()

      {

          return View();

      }

      [HttpPost]

      public List<'object> GetSalesdata()

      {

          List<'object''> result = new List<'object''>();

          List<string> labels = _db.Salestable.Select(p => p.MonthName).ToList();

          result.Add(labels);

          List<int> salesNumber = _db.Salestable.Select(p => p.TotalSales).ToList();

          result.Add(salesNumber);



          return result;

      }

ShowSalesData View: Design the view that presents the chart, with a Show Sales Data button. When the button is clicked, the chart appears in the canvas.

ShowSalesData view with a canvas and chart type dropdown

To show the data in the charts, we use a canvas and a drop-down list for the chart type. Based on the selected chart type, we draw the data in the canvas using an Ajax call to the controller action. The complete JavaScript code is shown in the image below.


JavaScript code that loads sales data with Ajax and draws the Chart.js chart