Create Free Charts Using Chart.js In ASP.NET MVC

You might think what is chart.js? You only have an idea that it's about charts and yes, you are right. We are going to create charts, using Chart.js .

You might think do we need to pay for using this tool?.

Chart.js is an open source and is available under MIT license.

It is free to use. We are going to use it with MVC Application in the next part. I will show how to use it with Webforms and AngularJS.



For details visit the site.

Let’s start with creating charts, using Chart.js in a step by step manner.

Let's start with the database first.

Database first

We are going to create 5 tables in the database and these tables' data is what we are going to display in the charts.


Fig 1. Database structure

CountryMaster table

This table will have the data of all countries with the name and ID. 


StateMaster table

This table will have data of all the states related to the country with the name and ID. 



CityMaster table

This table will have the data of all the cities related to the states with the name and ID. 



Producttable

This table will have the data of all the cities related to the states with the name and ID. 



ProductSalestable

This table will have the data of the product sales, according to the country, state, city.



After understanding the tables, next step is we are going to store the procedure for pulling the data from the database.

I will just display the name of the stored procedure, I am going provide it for the download. 

Stored procedure

Usp_GetTotalsalesStatewise

Output



Usp_GetTotalsalesProductwise

Output



Usp_GetTotalsalesCitieswise

Output



After complete understanding of the database part, we are going to create MVC Application.

Creating MVC Application

Open Visual Studio IDE on the start page of IDE, select New Project link and after selecting the link, a new dialog will pop up with the name New Project. In this dialog, at left bar, select Templates. Inside it, select Visual C# and inside it, select Web and after selecting middle panel, you will see the names of various Web project Templates, where we are going choose “ASP.NET MVC 4 Web Application ” and then we are going to name our project as “DemoChart” and click OK button to create the project.


Fig 2. Creating MVC Application

After clicking OK button, a new dialog will pop up with the name “New ASP.NET MVC 4 Project”. In this dialog, we are going to select template, where we want to develop an Application, where we are going to choose basic template and finally click OK button.


Fig 3. Choosing Project Template

Project structure after creating project


Fig 4. Project Structure after creating new project

After creating the project, we want some component, which will help us to get the data from the database.

Add Dapper ORM Reference from Nugets to Project

To add dapper ORM from NuGet Package Manager, just right click on the project and select - Manage NuGet Packages, a new dialog will pop up with the name “Manage NuGet Packages”. In search box, type Dapper, select “Dapper dot net” and click install button will be installed in the project.


Fig 5. Installing Dapper ORM in DemoChart Project

View after installing Dapper


Fig 6. After Installing Dapper ORM in DemoChart Project

In the next step, we are going add the folder with the name Repository and in the folder, we are going to add an Interface and Concrete class.

Adding Repository Folder

Just right click on the project, select Add and inside it, select New Folder and name Folder as Repository.

Fig 7. Adding Repository Folder to project

After adding the folder, we are going to using Repository pattern to get the data from the database.

Adding Interface

Adding Interface with the name “ICharts” in Repository folder and just declaring a method in it with the name ProductWiseSales, which has 2 strings as output.

CodeSnippet of ICharts Interface

  1. using DemoChart.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6.   
  7. namespace DemoChart.Repository  
  8. {  
  9.     public interface ICharts  
  10.     {  
  11.         void ProductWiseSales(out string MobileCountList, out string ProductList);  
  12.     }  
  13. }  
After adding an inteface ICharts, we are going to add Concrete Class ChartsConcrete.

Adding Concrete Class

Add the class with the name “ChartsConcrete” in Repository folder. This class will inherit ICharts interface .

CodeSnippet of ChartsConcrete class
  1. using DemoChart.Models;  
  2. using System.Configuration;  
  3. using System.Data.SqlClient;  
  4. using System.Linq;  
  5. using Dapper;  
  6. using System.Data;  
  7.   
  8. namespace DemoChart.Repository  
  9. {  
  10.     public class ChartsConcrete : ICharts  
  11.     {  
  12.         public void ProductWiseSales(out string MobileCountList, out string ProductList)  
  13.         {  
  14.             using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString()))  
  15.             {  
  16.                 var productdata = con.Query<ProductModel>("Usp_GetTotalsalesProductwise"nullnulltrue, 0, CommandType.StoredProcedure).ToList();  
  17.   
  18.                 var MobileSalesCounts = (from temp in productdata  
  19.                                          select temp.MobileSalesCount).ToList();  
  20.   
  21.                 var ProductNames = (from temp in productdata  
  22.                                     select temp.ProductName).ToList();  
  23.   
  24.                 MobileCountList = string.Join(",", MobileSalesCounts);  
  25.   
  26.                 ProductList = string.Join(",", ProductNames);  
  27.             }  
  28.         }  
  29.     }  
  30. }  
In the code snippet, you can see we have inherited ICharts interface and method inside it. To pull the data from the database, we need SQL connection with the database, which I have created with name [“Connection”]. Afterwards, we are going use the stored procedure to get data from data using Dapper ORM and map data base object to domain object. Here we are going to receive List of ProductModel as an output. We are going to seperate Mobile Sales count and Product name in the 2 different strings. We are joining the values with the help of [string.Join","] and push them to there individual string.

After adding Concrete Class ChartsConcrete, we are going add controller with the name DashboardController.

Adding DashboardController

To add the Controller, just right click on Controller folder and select Add. Inside it, select Controller. Afterwards, select Controller; a new dialog will popup with the name Add Controller. In the dialog, we are going to name our controller as DashboardController and in the template, we are going to select “Empty MVC Controller” and click Add button.


Fig 8. Adding Dashboard Controller

Project structure


Fig 9. Project structure after adding Dashboard Controller

We are going to do a change i.e. change Action method from Index to BarChart .

CodeSnippet of BarChart Action Method
  1. [HttpGet]  
  2. public ActionResult BarChart()  
  3. {  
  4.    return View();  
  5. }  
Now, after changing the name of Action Method, get the data from Concrete class and push this data to View to display the charts.

Creating Object of ChartsConcrete Class

In Constuctor of DashboardController, we are going to Create object of ChartsConcrete class. After creating an object, we are going to call ProductWiseSales Method from ChartsConcrete class and declare 2 output parameters in which we are going to get the data.

This data needs to be assigned to an individual viewbag.

CodeSnippet of Dashboard Controller
  1. using DemoChart.Repository;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace DemoChart.Controllers  
  9. {  
  10.     public class DashboardController : Controller  
  11.     {  
  12.         ICharts _ICharts;  
  13.         public DashboardController()  
  14.         {  
  15.             _ICharts = new ChartsConcrete();      
  16.         }  
  17.   
  18.         [HttpGet]  
  19.         public ActionResult BarChart()  
  20.         {  
  21.             try  
  22.             {  
  23.                 string tempMobile = string.Empty;  
  24.                 string tempProduct = string.Empty;  
  25.                 _ICharts.ProductWiseSales(out tempMobile, out tempProduct);  
  26.                 ViewBag.MobileCount_List = tempMobile.Trim();  
  27.                 ViewBag.Productname_List = tempProduct.Trim();  
  28.   
  29.                 return View();  
  30.             }  
  31.             catch (Exception)  
  32.             {              
  33.                 throw;  
  34.             }  
  35.         }  
  36.     }  
  37. }  
Now, we have got every thing ready to push to be viewed in the next step. We are going to create BarChart View.

Adding View [BarChart]

To add View, just right click inside BarChart Action Method. A list of Menus will be displayed. In it, select Add View and a new dialog will pop up with the name “Add View”. The name of View will be similar to the name of ActionMethod [“BarChart”] and finally click Add button.


Fig 10. Adding View with name BarChart

Snapshot is given below to add view.


Fig 11. Folder view after adding BarChart View

After adding BarChart View, we are going to work with charts.js to plot the data, which we have sent from Controller.

Adding Chart.js on [BarChart] View

It's too simple to create charts. Using Chart.js, we do not require DLL files to add reference or any compatibility issue.

Add the reference of Chart.js to View.

Step 1
  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7. <head>  
  8.     <meta name="viewport" content="width=device-width" />  
  9.     <title>Charts</title>  
  10.     <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>  
  11. </head>  
  12. <body>  
  13. </body>  
  14. </html>  
Step 2

Fig 12. Snapshot while setting the parameters

Step 3

Fig 13. Snapshot while setting the parameters

Step 4

Fig 14. Snapshot while adding canvas tag

BarChart

The complete code snippet of Barchart.cshtml is given below. 
  1. @{  
  2.     Layout = null;  
  3. }  
  4. <!DOCTYPE html>  
  5. <html>  
  6. <head>  
  7.     <meta name="viewport" content="width=device-width" />  
  8.     <title>Charts</title>  
  9.     <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>  
  10.     <script>  
  11.         var barChartData =  
  12.             {  
  13.                 labels: [@Html.Raw(ViewBag.Productname_List)],  
  14.                 datasets: [{  
  15.                     label: 'ProductWise Sales Count',  
  16.                     backgroundColor: [  
  17.                         "#f990a7",  
  18.                         "#aad2ed",  
  19.                         "#9966FF",  
  20.                         "#99e5e5",  
  21.                         "#f7bd83",  
  22.                     ],  
  23.                     borderWidth: 2,  
  24.                     data: [@ViewBag.MobileCount_List]  
  25.                 }]  
  26.             };  
  27.   
  28.             window.onload = function () {  
  29.                 var ctx1 = document.getElementById("barcanvas").getContext("2d");  
  30.                 window.myBar = new Chart(ctx1,  
  31.                     {  
  32.                         type: 'bar',  
  33.                         data: barChartData,  
  34.                         options:  
  35.                             {  
  36.                                 title:  
  37.                                 {  
  38.                                     display: true,  
  39.                                     text: "ProductWise Sales Count"  
  40.                                 },  
  41.                                 responsive: true,  
  42.                                 maintainAspectRatio: true  
  43.                             }  
  44.                     });  
  45.             }  
  46.     </script>  
  47. </head>  
  48. <body>  
  49.     <div style="text-align: center">  
  50.         <canvas id="barcanvas"></canvas>  
  51.     </div>  
  52.     <div style="text-align: center">  
  53.         Disclaimer:- This data is for demo it is   
  54.         not real data it wont relate to any company  
  55.     </div>  
  56. </body>  
  57. </html>  
Now, after complete understanding of the code snippet in step by step manner, just save your code and run the Application to check how you charts have been plotted.

Final Output


Fig 15. Barchart view

Snapshot of Dashboard Controller with all Action Method.

In this snapshot, we have added new action method.


Fig 16. Snapshot of Dashboard Controller with all Action Method

PieChart

The complete code snippet of PieChart.cshtml is given below. 
  1. @{  
  2.     Layout = null;  
  3. }  
  4. <!DOCTYPE html>  
  5. <html>  
  6. <head>  
  7.     <meta name="viewport" content="width=device-width" />  
  8.     <title>Pie Charts</title>  
  9.     <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>  
  10.     <script>  
  11.         var PieChartData =  
  12.             {  
  13.                 labels: [@Html.Raw(ViewBag.Productname_List)],  
  14.                 datasets: [{  
  15.                     label: 'ProductWise Sales Count',  
  16.                     backgroundColor: [  
  17.                         "#f990a7",  
  18.                         "#aad2ed",  
  19.                         "#9966FF",  
  20.                         "#99e5e5",  
  21.                         "#f7bd83",  
  22.                     ],  
  23.                     borderWidth: 2,  
  24.                     data: [@ViewBag.MobileCount_List]  
  25.                 }]  
  26.             };  
  27.   
  28.             window.onload = function () {  
  29.                 var ctx1 = document.getElementById("Piecanvas").getContext("2d");  
  30.                 window.myBar = new Chart(ctx1,  
  31.                     {  
  32.                         type: 'pie',  
  33.                         data: PieChartData,  
  34.                         options:  
  35.                             {  
  36.                                 title:  
  37.                                 {  
  38.                                     display: true,  
  39.                                     text: "ProductWise Sales Count"  
  40.                                 },  
  41.                                 responsive: true,  
  42.                                 maintainAspectRatio: true  
  43.                             }  
  44.                     });  
  45.             }  
  46.     </script>  
  47. </head>  
  48. <body>  
  49.     <div style="text-align: center">  
  50.         <canvas id="Piecanvas"></canvas>  
  51.     </div>  
  52.     <div style="text-align: center">  
  53.         Disclaimer:- This data is for demo it is   
  54.         not real data it wont relate to any company  
  55.     </div>  
  56. </body>  
  57.   
  58. </html>  
Final Output


Fig 17. Pie Chart view

LineChart

The complete code snippet of Linechart.cshtml is given below. 
  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7. <head>  
  8.     <meta name="viewport" content="width=device-width" />  
  9.     <title>Line Charts</title>  
  10.     <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>  
  11.     <script>  
  12.         var LineChartData =  
  13.             {  
  14.                 labels: [@Html.Raw(ViewBag.Productname_List)],  
  15.                 datasets: [{  
  16.                     label: 'ProductWise Sales Count',  
  17.                     backgroundColor: "rgba(75,192,192,0.4)",  
  18.                     borderWidth: 2,  
  19.                     data: [@ViewBag.MobileCount_List]  
  20.                 }]  
  21.             };  
  22.   
  23.             window.onload = function () {  
  24.                 var ctx1 = document.getElementById("Linecanvas").getContext("2d");  
  25.                 window.myBar = new Chart(ctx1,  
  26.                     {  
  27.                         type: 'line',  
  28.                         data: LineChartData,  
  29.                         options:  
  30.                             {  
  31.                                 title:  
  32.                                 {  
  33.                                     display: true,  
  34.                                     text: "ProductWise Sales Count"  
  35.                                 },  
  36.                                 responsive: true,  
  37.                                 maintainAspectRatio: true  
  38.                             }  
  39.                     });  
  40.             }  
  41.     </script>  
  42. </head>  
  43. <body>  
  44.     <div style="text-align: center">  
  45.         <canvas id="Linecanvas"></canvas>  
  46.     </div>  
  47.     <div style="text-align: center">  
  48.         Disclaimer:- This data is for demo it is   
  49.         not real data it wont relate to any company  
  50.     </div>  
  51. </body>  
  52.   
  53. </html>  
Final Output


Fig 18. Line Chart view

Doughnut Chart

The complete code snippet of DoughnutChart.cshtml is given below.
  1. @{  
  2.     Layout = null;  
  3. }  
  4. <!DOCTYPE html>  
  5. <html>  
  6. <head>  
  7.     <meta name="viewport" content="width=device-width" />  
  8.     <title>Pie Charts</title>  
  9.     <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>  
  10.     <script>  
  11.         var DoughnutChartData =  
  12.             {  
  13.                 labels: [@Html.Raw(ViewBag.Productname_List)],  
  14.                 datasets: [{  
  15.                     label: 'ProductWise Sales Count',  
  16.                     backgroundColor: [  
  17.                         "#f990a7",  
  18.                         "#aad2ed",  
  19.                         "#9966FF",  
  20.                         "#99e5e5",  
  21.                         "#f7bd83",  
  22.                     ],  
  23.                     borderWidth: 2,  
  24.                     data: [@ViewBag.MobileCount_List]  
  25.                 }]  
  26.             };  
  27.   
  28.             window.onload = function () {  
  29.                 var ctx1 = document.getElementById("Doughnutcanvas").getContext("2d");  
  30.                 window.myBar = new Chart(ctx1,  
  31.                     {  
  32.                         type: 'doughnut',  
  33.                         data: DoughnutChartData,  
  34.                         options:  
  35.                             {  
  36.                                 title:  
  37.                                 {  
  38.                                     display: true,  
  39.                                     text: "ProductWise Sales Count"  
  40.                                 },  
  41.                                 responsive: true,  
  42.                                 maintainAspectRatio: true  
  43.                             }  
  44.                     });  
  45.             }  
  46.     </script>  
  47. </head>  
  48. <body>  
  49.     <div style="text-align: center">  
  50.         <canvas id="Doughnutcanvas"></canvas>  
  51.     </div>  
  52.     <div style="text-align: center">  
  53.         Disclaimer:- This data is for demo it is   
  54.         not real data it wont relate to any company  
  55.     </div>  
  56. </body>  
  57.   
  58. </html>  
Final Output


Fig 19. Doughnut Chart view

Conclusion

In this article, we have learned how to create charts, using Chart.js. I hope, you enjoyed the journey. Stay tuned, as we keep coming with the new stuff.


Similar Articles