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
- using DemoChart.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace DemoChart.Repository
- {
- public interface ICharts
- {
- void ProductWiseSales(out string MobileCountList, out string ProductList);
- }
- }
Adding Concrete Class
Add the class with the name “ChartsConcrete” in Repository folder. This class will inherit ICharts interface .
CodeSnippet of ChartsConcrete class
- using DemoChart.Models;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.Linq;
- using Dapper;
- using System.Data;
- namespace DemoChart.Repository
- {
- public class ChartsConcrete : ICharts
- {
- public void ProductWiseSales(out string MobileCountList, out string ProductList)
- {
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString()))
- {
- var productdata = con.Query<ProductModel>("Usp_GetTotalsalesProductwise", null, null, true, 0, CommandType.StoredProcedure).ToList();
- var MobileSalesCounts = (from temp in productdata
- select temp.MobileSalesCount).ToList();
- var ProductNames = (from temp in productdata
- select temp.ProductName).ToList();
- MobileCountList = string.Join(",", MobileSalesCounts);
- ProductList = string.Join(",", ProductNames);
- }
- }
- }
- }
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
- [HttpGet]
- public ActionResult BarChart()
- {
- return View();
- }
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
- using DemoChart.Repository;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace DemoChart.Controllers
- {
- public class DashboardController : Controller
- {
- ICharts _ICharts;
- public DashboardController()
- {
- _ICharts = new ChartsConcrete();
- }
- [HttpGet]
- public ActionResult BarChart()
- {
- try
- {
- string tempMobile = string.Empty;
- string tempProduct = string.Empty;
- _ICharts.ProductWiseSales(out tempMobile, out tempProduct);
- ViewBag.MobileCount_List = tempMobile.Trim();
- ViewBag.Productname_List = tempProduct.Trim();
- return View();
- }
- catch (Exception)
- {
- throw;
- }
- }
- }
- }
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
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Charts</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
- </head>
- <body>
- </body>
- </html>

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.
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Charts</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
- <script>
- var barChartData =
- {
- labels: [@Html.Raw(ViewBag.Productname_List)],
- datasets: [{
- label: 'ProductWise Sales Count',
- backgroundColor: [
- "#f990a7",
- "#aad2ed",
- "#9966FF",
- "#99e5e5",
- "#f7bd83",
- ],
- borderWidth: 2,
- data: [@ViewBag.MobileCount_List]
- }]
- };
- window.onload = function () {
- var ctx1 = document.getElementById("barcanvas").getContext("2d");
- window.myBar = new Chart(ctx1,
- {
- type: 'bar',
- data: barChartData,
- options:
- {
- title:
- {
- display: true,
- text: "ProductWise Sales Count"
- },
- responsive: true,
- maintainAspectRatio: true
- }
- });
- }
- </script>
- </head>
- <body>
- <div style="text-align: center">
- <canvas id="barcanvas"></canvas>
- </div>
- <div style="text-align: center">
- Disclaimer:- This data is for demo it is
- not real data it wont relate to any company
- </div>
- </body>
- </html>
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.
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Pie Charts</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
- <script>
- var PieChartData =
- {
- labels: [@Html.Raw(ViewBag.Productname_List)],
- datasets: [{
- label: 'ProductWise Sales Count',
- backgroundColor: [
- "#f990a7",
- "#aad2ed",
- "#9966FF",
- "#99e5e5",
- "#f7bd83",
- ],
- borderWidth: 2,
- data: [@ViewBag.MobileCount_List]
- }]
- };
- window.onload = function () {
- var ctx1 = document.getElementById("Piecanvas").getContext("2d");
- window.myBar = new Chart(ctx1,
- {
- type: 'pie',
- data: PieChartData,
- options:
- {
- title:
- {
- display: true,
- text: "ProductWise Sales Count"
- },
- responsive: true,
- maintainAspectRatio: true
- }
- });
- }
- </script>
- </head>
- <body>
- <div style="text-align: center">
- <canvas id="Piecanvas"></canvas>
- </div>
- <div style="text-align: center">
- Disclaimer:- This data is for demo it is
- not real data it wont relate to any company
- </div>
- </body>
- </html>

Fig 17. Pie Chart view
LineChart
The complete code snippet of Linechart.cshtml is given below.
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Line Charts</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
- <script>
- var LineChartData =
- {
- labels: [@Html.Raw(ViewBag.Productname_List)],
- datasets: [{
- label: 'ProductWise Sales Count',
- backgroundColor: "rgba(75,192,192,0.4)",
- borderWidth: 2,
- data: [@ViewBag.MobileCount_List]
- }]
- };
- window.onload = function () {
- var ctx1 = document.getElementById("Linecanvas").getContext("2d");
- window.myBar = new Chart(ctx1,
- {
- type: 'line',
- data: LineChartData,
- options:
- {
- title:
- {
- display: true,
- text: "ProductWise Sales Count"
- },
- responsive: true,
- maintainAspectRatio: true
- }
- });
- }
- </script>
- </head>
- <body>
- <div style="text-align: center">
- <canvas id="Linecanvas"></canvas>
- </div>
- <div style="text-align: center">
- Disclaimer:- This data is for demo it is
- not real data it wont relate to any company
- </div>
- </body>
- </html>

Fig 18. Line Chart view
Doughnut Chart
The complete code snippet of DoughnutChart.cshtml is given below.
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Pie Charts</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
- <script>
- var DoughnutChartData =
- {
- labels: [@Html.Raw(ViewBag.Productname_List)],
- datasets: [{
- label: 'ProductWise Sales Count',
- backgroundColor: [
- "#f990a7",
- "#aad2ed",
- "#9966FF",
- "#99e5e5",
- "#f7bd83",
- ],
- borderWidth: 2,
- data: [@ViewBag.MobileCount_List]
- }]
- };
- window.onload = function () {
- var ctx1 = document.getElementById("Doughnutcanvas").getContext("2d");
- window.myBar = new Chart(ctx1,
- {
- type: 'doughnut',
- data: DoughnutChartData,
- options:
- {
- title:
- {
- display: true,
- text: "ProductWise Sales Count"
- },
- responsive: true,
- maintainAspectRatio: true
- }
- });
- }
- </script>
- </head>
- <body>
- <div style="text-align: center">
- <canvas id="Doughnutcanvas"></canvas>
- </div>
- <div style="text-align: center">
- Disclaimer:- This data is for demo it is
- not real data it wont relate to any company
- </div>
- </body>
- </html>

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.

Ankit ShuklaPosted Nov 16, 2021, 11:13 AM
Sir please upload procedure
Byron ByronPosted Jul 13, 2020, 10:16 AM
Thanks for the tutorial, but the stored procedure it is not in zip file.
Hemu Kumar ShriwastawPosted Apr 4, 2020, 12:57 PM
Thank for nice explanation
Touhidul IslamPosted Mar 15, 2020, 11:58 AM
Where is db Script?
mohan singhPosted Oct 17, 2019, 6:07 AM
Thanks, for nice explanation
urang kitoPosted Sep 2, 2019, 2:48 AM
Hi Sai, thank you. I adapted to .Net Core 2.2 and it works well.
uma sinhaPosted Jun 13, 2019, 1:19 AM
Stored procedure is not there....how you created ?
shinobiencisoPosted Apr 30, 2019, 11:51 AM
Where are the Stored Procedures?
A TroungPosted Feb 20, 2019, 11:00 PM
I could not find the stored procedure: Usp_GetTotalsalesStatewise, Usp_GetTotalsalesProductwise,Usp_GetTotalsalesCitieswise in your download code.
yuwei kePosted Jan 10, 2019, 8:35 PM
I got a problem. It shows that javascript error : Apple is undefined.
Jitendra WaghalePosted Jan 6, 2019, 2:12 PM
@Sai - Too wonderful Article, Thank you very much, Saved lot of time.
Digamber SutarPosted Jul 31, 2018, 11:37 PM
How to use it in webforms?
StanPosted May 27, 2018, 5:13 AM
Thank you. Worked great!
Ashmeen CloetePosted Jan 17, 2018, 6:46 AM
Enjoyed the tutorial, amazing work. (var Data = con.Query<Model>("sp_", null, null, true, 0, CommandType.StoredProcedure).ToList(); ) You use this to get or identify the stored procedure, however i would like to filter the returning data by adding input parameters in the stored procedure, for example giving two dates for it to filter between those dates. Any ideas of achieving this. I'm still a beginner.
Muhammad YounisPosted Jan 11, 2018, 6:52 AM
Thanks to all for support & help.
bhupendr singhPosted Jan 9, 2018, 4:20 AM
Regarding Doughnut chart, backgroundColor: ["rgba(128, 0, 128, 0.5)", "rgba(255, 165, 0, 0.5)","rgba(0, 128, 0, 0.5)","rgba(128, 128, 128, 0.5)"],above hard code is working but when I create my own string on fly then only last color is painting in every piece of doughnut, below is the codebackgroundColor: [colr], where color is string and equals to "rgba(128, 0, 128, 0.5)", "rgba(255, 165, 0, 0.5)","rgba(0, 128, 0, 0.5)","rgba(128, 128, 128, 0.5)"
Muhammad YounisPosted Jan 2, 2018, 12:53 PM
Its very helpful.But how to show all charts in a single page?
Muhammad YounisPosted Jan 2, 2018, 12:50 PM
How to show all charts in single page?
Sagar Pandurang KapPosted Dec 4, 2017, 3:40 AM
Nice post. Showing data using charts looks Impressive and easy to understand.
prashant vishnoiPosted Nov 4, 2017, 5:55 AM
Thanks a lot. its very helpful.
SubashPosted Oct 12, 2017, 11:52 PM
Very excellent bro
Mahesh KorviPosted Jun 15, 2017, 5:30 AM
I couldnt find database structure and storedproc beo
hacoPosted May 25, 2017, 5:13 PM
I can't find Stored procedure or database in Download Files please help me!!
f rPosted Apr 7, 2017, 1:17 PM
I can't find Stored procedure or database in Download Files please guide me
Rahul YadavPosted Apr 5, 2017, 3:29 AM
Please share database script for the same code
Pravin KolhePosted Dec 21, 2016, 7:57 AM
Hi Sai, please help to pass data & labels from controller to view for ChartJS.. I tried to do and debugged. I could see "Values" in viewbag variables but graph/chart is not shown or rendered on UI?
Vinay SakpalPosted Oct 15, 2016, 5:19 AM
Great Article...!!!
farooq smdPosted Oct 14, 2016, 1:18 PM
Nice