In Focus

ASP.NET MVC 5 - JavaScript C3 Chart Library📊 - Generate Gauge Chart And Customize It

In this article, I will demonstrate how to generate a Gauge chart using C3 Chart JavaScript Library to view the population by gender from a database using Entity Framework in ASP.NET MVC5.

Introduction
 
In this article, I will demonstrate how to generate a Gauge Chart using C3 Chart JavaScript Library to view the population stats by gender from a database using Entity Framework in ASP.NET MVC5. Gauge Chart supports three types of values - Min, Max, and Data. By default, min parameter would be a 0 and will show the value in %. Here, we are going to assign the total population value as Max and gender values as data. Okay, let us move forward to generate the chart.
 
Prerequisites
  • Visual Studio
  • SQL Server
  • Basic Knowledge of ASP.NET MVC
  • Basic Knowledge of Entity Framework
  • Basic Knowledge of jQuery
  • Basic Knowledge of CSS
Article Flow
  • Create a table in a database with the list of the population by gender and write a stored procedure.
  • Create ASP.NET MVC Empty project
  • Configure Entity Framework with database and application
  • Create a Controller and View
  • Install C3 chart from NuGet and enable it in our application
  • Generate Gauge Chart
  • Customize Chart
Create a table in a database with the list of the population by gender and write a stored procedure
 
First, we will create a table in SQL Server to generate a gauge chart with the gender population in ASP.NET MVC Web application. I have created a table called "Population" with the following design.
 
 
 
Execute the below query to create a table with the above design.
  1. CREATE TABLE [dbo].[Population](  
  2. [Id] [bigint] IDENTITY(1,1) NOT NULL,  
  3. [Male] [floatNULL,  
  4. [Female] [floatNULL,  
  5. [Others] [floatNULL,  
  6. [Country] [nvarchar](50) NULL,  
  7. [MonthAndYear] [datetime] NULL,  
  8. CONSTRAINT [PK_Population] PRIMARY KEY CLUSTERED  
  9. (  
  10. [Id] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  12. ON [PRIMARY]  
  13. GO  
And now, add a few dummy values to view in the gauge chart. I have added some rows as shown below.
 
 
 
To add these dummy data values of the population by gender, execute the below insert queries.
  1. USE [CSharpCorner]  
  2. GO  
  3. SET IDENTITY_INSERT [dbo].[Population] ON  
  4. GO  
  5. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (1, 150, 200, 10, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  6. GO  
  7. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (2, 200, 100, 5, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  8. GO  
  9. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (3, 200, 300, 4, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  10. GO  
  11. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (4, 300, 150, 7, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  12. GO  
  13. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (5, 400, 300, 6, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  14. GO  
  15. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (6, 200, 500, 3, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  16. GO  
  17. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (7, 100, 200, 2, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  18. GO  
  19. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (8, 300, 100, 8, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  20. GO  
  21. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (9, 500, 200, 6, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  22. GO  
  23. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (10, 300, 100, 11, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  24. GO  
  25. INSERT [dbo].[Population] ([Id], [Male], [Female], [Others], [Country], [MonthAndYear]) VALUES (11, 100, 50, 10, N'India'CAST(N'2018-12-12T02:16:13.380' AS DateTime))  
  26. GO  
  27. SET IDENTITY_INSERT [dbo].[Population] OFF  
  28. GO  
Create ASP.NET MVC Empty project 
  • To create an ASP.NET MVC empty project, follow the below steps one by one. Here, I have used Visual Studio 2017.
  • Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it "GaugeChartDemo".
  • Now, click OK.
  • Then, select Empty ASP.NET MVC template and click OK to create the project.
  • Once you click OK, the project will be created with the basic architecture of MVC. If you are not aware of how to create an Empty ASP.NET Web Application, please visit  Step 1 and Step 2 to learn.
Once you complete these steps, you will get the screen as below.
 
 
 
Configure Entity Framework with database and application
 
Here, I have already discussed how to configure and implement a database-first approach. In the meantime, choose your created table with Entity Framework. Once we do our configuration with SQL table "Population" from CSharpCorner database and with our application, we will get the below screen as the succeeding configuration.
 
 
 
Create a Controller and View
 
Now, create an empty Controller and View. Here, I created a Controller with the name of "GaugeController". Whenever we create an empty Controller, it is created with an empty Index action method. And create an empty View of this action method "Index".
 
Install C3 chart from NuGet and enable it in our application
 
I discussed C3 Installation and integration in  My Article.
 
Generate a Gauge Chart Controller
 
Now, write the logic in your Controller to fetch the data from the database and return that data as JSON to the View. In the below code, you can see that I have created a "GaugeChart" action to fetch the data from the database using Entity Framework and SqlQuery.Before that let's write the Logic using stored procedures to get the sum of male, female, others and total population.
  1. USE [CSharpCorner]  
  2. GO  
  3. /****** Object: StoredProcedure [dbo].[GAUGE_CHART_sp] Script Date: 12/22/2018 12:02:57 AM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE PROCEDURE [dbo].[GAUGE_CHART_sp]  
  9. AS  
  10. BEGIN  
  11. select SUM(Male) as Male, SUM(Female) as Female,SUM(Others) as Others, SUM(Male)+SUM(Female)+SUM(Others) as Total from Population  
  12. END  
Now, execute the stored procedure. Let's render this result in the chart.
 
 
 
Now write the logic in the controller to get the value from the database.
  1. public ActionResult GaugeChart() {  
  2.     CSharpCornerEntities entities = new CSharpCornerEntities();  
  3.     var test = entities.Database.SqlQuery < GenderPopulation > ("exec GAUGE_CHART_sp").ToList();  
  4.     return Json(test, JsonRequestBehavior.AllowGet);  
  5. }  
Use the Below model to bind the data.
  1. public class GenderPopulation {  
  2.     public Nullable < double > Male {  
  3.         get;  
  4.         set;  
  5.     } = 0;  
  6.     public Nullable < double > Female {  
  7.         get;  
  8.         set;  
  9.     } = 0;  
  10.     public Nullable < double > Others {  
  11.         get;  
  12.         set;  
  13.     } = 0;  
  14.     public Nullable < double > Total {  
  15.         get;  
  16.         set;  
  17.     } = 0;  
  18. }  
View
 
In View, add a Controller which will act as a gauge chart in our application. For that, I have added one div with the name of GaugeChart.
  1. <div id="GaugeChart"></div>   
Script
 
Now, write the logic in jQuery AJAX to get the JSON data from your controller action. In the below code, you can see that we are trying to retrieve the data from BarChart action under chart controller.
  1. $.ajax({  
  2.     type: "GET",  
  3.     url: "/Gauge/GaugeChart",  
  4.     data: {},  
  5.     contentType: "application/json; charset=utf-8",  
  6.     dataType: "json",  
  7.     success: function(response) {  
  8.         successFunc(response);  
  9.     },  
  10. });  
After getting JSON data from our controller, bind the JSON data to the chart as below.
 
c3.generate({ -> This is the predefined keyword c3 charts to generate charts on respective controls
 
bindto: '#GaugeChart', -> Changing our div control to Bar chart control or all bar chart features will bind to this control
 
columns: [['Male', jsondata[0].Male]-> We are getting values of males in first row
 
max: jsondata[0].Total, -> we did set the max value for gauge chart 
 
jsondata[0] -> We have only one row in json result; that's why we mentioned [0] to get first row value
 
type: 'gauge' -> It's to mention the type of chart we wanted to generate
 
color: {pattern: -> Combination color will be applied to our chart
  1. function successFunc(jsondata) {  
  2.     var chart = c3.generate({  
  3.         bindto: '#GaugeChart',  
  4.         data: {  
  5.             columns: [  
  6.                 ['Male', jsondata[0].Male]  
  7.             ],  
  8.             type: 'gauge',  
  9.         },  
  10.         gauge: {  
  11.             max: jsondata[0].Total,  
  12.             label: true  
  13.         },  
  14.         color: {  
  15.             pattern: ['#FF0000''#F97600'],  
  16.         },  
  17.     });  
  18. }  
Now run your application
 
 
Now, view all gender population by setting the timeout in JavaScript.
  1. setTimeout(function() {  
  2.     chart.load({  
  3.         columns: [  
  4.             ['Female', jsondata[0].Female]  
  5.         ]  
  6.     });  
  7. }, 1000);  
  8. setTimeout(function() {  
  9.     chart.load({  
  10.         columns: [  
  11.             ['Others', jsondata[0].Others]  
  12.         ]  
  13.     });  
  14. }, 2000);  
Now, run your application.
 
 
Customize Chart
 
   Let's do some customization on this gauge chart. 
  • Change color of Min Value Label  
    1. .c3-chart-arcs .c3-chart-arcs-gauge-min {  
    2.    fill: black;  
    3. }  
  • Change color of Max Value Label   
    1. .c3-chart-arcs .c3-chart-arcs-gauge-max {  
    2.    fill: red;  
    3. }  
  • Change color of % (data) Value 
    1. .c3-chart-arc .c3-gauge-value {  
    2.    fill: teal;  
    3. }  
Run your Application, In below image you can see that label has been changed.
 
 
Complete View 
  1. @ {  
  2.     ViewBag.Title = "Chart";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. } < style > .c3 - chart - arcs.c3 - chart - arcs - gauge - min {  
  5.     fill: black;  
  6. }.c3 - chart - arcs.c3 - chart - arcs - gauge - max {  
  7.     fill: red;  
  8. }.c3 - chart - arc.c3 - gauge - value {  
  9.     fill: teal;  
  10. } < /style> < br / > < div id = "GaugeChart" > < /div> < script type = "text/javascript" > $(document).ready(function() {  
  11.     $.ajax({  
  12.         type: "GET",  
  13.         url: "/Gauge/GaugeChart",  
  14.         data: {},  
  15.         contentType: "application/json; charset=utf-8",  
  16.         dataType: "json",  
  17.         success: function(response) {  
  18.             successFunc(response);  
  19.         },  
  20.     });  
  21.   
  22.     function successFunc(jsondata) {  
  23.         var chart = c3.generate({  
  24.             bindto: '#GaugeChart',  
  25.             data: {  
  26.                 columns: [  
  27.                     ['Male', jsondata[0].Male]  
  28.                 ],  
  29.                 type: 'gauge',  
  30.             },  
  31.             gauge: {  
  32.                 max: jsondata[0].Total,  
  33.                 label: true  
  34.             },  
  35.             color: {  
  36.                 pattern: ['#F97600'],  
  37.             },  
  38.         });  
  39.         setTimeout(function() {  
  40.             chart.load({  
  41.                 columns: [  
  42.                     ['Female', jsondata[0].Female]  
  43.                 ]  
  44.             });  
  45.         }, 1000);  
  46.         setTimeout(function() {  
  47.             chart.load({  
  48.                 columns: [  
  49.                     ['Others', jsondata[0].Others]  
  50.                 ]  
  51.             });  
  52.         }, 2000);  
  53.     }  
  54. }); < /script>  
_Layout.cshtml 
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  7.     <title>@ViewBag.Title - My ASP.NET Application</title>  
  8.     <link href="~/Content/c3.css" rel="stylesheet" />  
  9.     <link href="~/Content/Site.css" rel="stylesheet" />  
  10.     <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  11.     <script src="~/Scripts/c3.min.js"></script>  
  12.     <script src="~/Scripts/d3.min.js"></script>  
  13.     <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  14. </head>  
  15.   
  16. <body>  
  17.     <div class="navbar navbar-inverse navbar-fixed-top">  
  18.         <div class="container">  
  19.             <div class="navbar-header">  
  20.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  21.                     <span class="icon-bar"></span>  
  22.                     <span class="icon-bar"></span>  
  23.                     <span class="icon-bar"></span>  
  24.                 </button> @Html.ActionLink("Gauge Chart""Index""Home"new { area = "" }, new { @class = "navbar-brand" }) </div>  
  25.             <div class="navbar-collapse collapse">  
  26.                 <ul class="nav navbar-nav">  
  27.                 </ul>  
  28.             </div>  
  29.         </div>  
  30.     </div>  
  31.     <div class="container body-content"> @RenderBody()  
  32.         <hr />  
  33.         <footer>  
  34.             <p>© @DateTime.Now.Year - My ASP.NET Application</p>  
  35.         </footer>  
  36.     </div>  
  37. </body>  
  38.   
  39. </html>  
Complete Controller
  1. using GaugeChartDemo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace GaugeChartDemo.Controllers {  
  8.     public class GaugeController: Controller {  
  9.         // GET: Gauge  
  10.         public ActionResult Index() {  
  11.             return View();  
  12.         }  
  13.         public ActionResult GaugeChart() {  
  14.             CSharpCornerEntities entities = new CSharpCornerEntities();  
  15.             var test = entities.Database.SqlQuery < GenderPopulation > ("exec GAUGE_CHART_sp").ToList();  
  16.             return Json(test, JsonRequestBehavior.AllowGet);  
  17.         }  
  18.         public class GenderPopulation {  
  19.             public Nullable < double > Male {  
  20.                 get;  
  21.                 set;  
  22.             } = 0;  
  23.             public Nullable < double > Female {  
  24.                 get;  
  25.                 set;  
  26.             } = 0;  
  27.             public Nullable < double > Others {  
  28.                 get;  
  29.                 set;  
  30.             } = 0;  
  31.             public Nullable < double > Total {  
  32.                 get;  
  33.                 set;  
  34.             } = 0;  
  35.         }  
  36.     }  
  37. }  
Refer to the attached project for reference and I did attach the demonstrated project without a package due to the size limit.
 
Summary
 
In this article, we have seen how to generate a C3 Gauge Chart in our ASP.NET MVC5 web application with JSON data using Entity Framework.
 
I hope you enjoyed this article. Your valuable feedback and comments about this article are always welcome.