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);
- }
- }
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
- 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);
- }
- }
- }
- }
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
- [HttpGet]
- public ActionResult BarChart()
- {
- return View();
- }
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
- 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;
- }
- }
- }
- }
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
- @{
- 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>
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.
- @{
- 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>
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.
- @{
- 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>
Final Output
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>
Final Output
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>
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.