ASP.NET MVC5 - Generate Pie Chart Using JavaScript C3 Chart Library And Entity Framework

Introduction
 
In this article, I will demonstrate how to generate a pie chart using C3 Chart JavaScript Library to view the country population from a database using Entity Framework in ASP.NET MVC5. Let's move forward.
 
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 country population values
  • 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 Chart
  • Customize Chart
Create a table in the database with a list of country population values
 
First, we will create a table in SQL Server to generate a chart with the country population details in ASP.NET MVC Web application. I have created a table called "Country" with the following design.
 
Generate Piechart using JavaScript C3 Chart Library and Entity Framework
 
Execute the below query to create a table with the above design.
  1. CREATE TABLE [dbo].[Country](  
  2. [CountryID] [bigint] IDENTITY(1,1) NOT NULL,  
  3. [CountryName] [nvarchar](250) NULL,  
  4. [CountryPopulation] [floatNULL,  
  5. CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED  
  6. (  
  7.    [CountryID] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10. GO  
And now, add a few dummy values to view in the pie chart. I have added some rows as shown below.
 
Generate Piechart using JavaScript C3 Chart Library and Entity Framework 
 
To add these dummy data values of the countrywise population, execute the below insert queries. 
  1. SET IDENTITY_INSERT [dbo].[Country] ON  
  2. GO  
  3. INSERT [dbo].[Country] ([CountryID], [CountryName], [CountryPopulation]) VALUES (1, N'India', 300)  
  4. GO  
  5. INSERT [dbo].[Country] ([CountryID], [CountryName], [CountryPopulation]) VALUES (2, N'UK', 200)  
  6. GO  
  7. INSERT [dbo].[Country] ([CountryID], [CountryName], [CountryPopulation]) VALUES (3, N'US', 100)  
  8. GO  
  9. SET IDENTITY_INSERT [dbo].[Country] OFF  
  10. GO  
Create ASP.NET MVC Empty project
  1. To create an ASP.NET MVC empty project, follow the below steps one by one. Here, I have used Visual Studio 2013.
  2. Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it "Piechart".
  3. Now, click OK.
  4. Then, select Empty ASP.NET MVC template and click OK to create the project.
  5. 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 Step1 and Step2 to learn.
Once you complete these steps, you will get the screen as below.
 
Generate Piechart using JavaScript C3 Chart Library and Entity Framework 
 
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 "Country" from CSharpCorner database and with our application, we will get the below screen as the succeeding configuration.
 
Generate Piechart using JavaScript C3 Chart Library and Entity Framework
 
Create a Controller and View
 
Now, create an empty Controller and View. Here, I created a Controller with the name of "ChartController". Whenever we create an empty Controller, it is created with an empty Index action method. And create an empty View to this action method "Index".
 
Install C3 chart from NuGet and enable it in our application
 
To use C3 chart features, we need to enable it to our application.
 
Manage NuGet Packages 

Generate Piechart using JavaScript C3 Chart Library and Entity Framework


Install C3 Chart
 
Browse the C3 chart and install it.
 
Generate Piechart using JavaScript C3 Chart Library and Entity Framework
 
After Installing the C3 charts, we will get the below supporting files into our application. You can see that we got a few CSS and JavaScript files for C3 and D3 chart.

Generate Piechart using JavaScript C3 Chart Library and Entity Framework 
 
Enable C3 chart Features 
 
To enable C3 chart features into our application, let's refer to those supporting files into our master layout(_layout.cshtml).
  1. <link href="~/Content/c3.css" rel="stylesheet" />  
  2. <link href="~/Content/Site.css" rel="stylesheet" />  
  3. <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  4. <script src="~/Scripts/c3.min.js"></script>  
  5. <script src="~/Scripts/d3.min.js"></script>  
  6. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
Controller 
 
Now, write a login 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 "PieChart" action to fetch the data from database using Entity Framework.
  1. using Piechart.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace Piechart.Controllers {  
  8.     public class ChartController: Controller {  
  9.         // GET: Chart  
  10.         public ActionResult Index() {  
  11.             return View();  
  12.         }  
  13.         public ActionResult PieChart() {  
  14.             CSharpCornerEntities entities = new CSharpCornerEntities();  
  15.             return Json(entities.Countries.ToList(), JsonRequestBehavior.AllowGet);  
  16.         }  
  17.     }  
  18. }  
View 
In View, add a Controller which will act as pie chart in our application. For that, I have added one div with the name of pieChart.
  1. <div id="pieChart"></div>   
Script
 
Now, write the login 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 Piechart action under chart controller.
  • var data = {}; -> to hold countrywise population in json format
  •  var countryNames = []; -> to hold only country names in array format
  • jsondata.forEach(function (e) { -> foreach method / Looping
  • countryNames.push(e.CountryName); -> we are pusing all country names into countryNames array
  • data[e.CountryName] = e.CountryPopulation; -> here, we are trying to add population countrywise
  • c3.generate({ -> This is the predefined keyword c3 charts to generate charts on respective control
  • bindto: '#pieChart', -> Changing our div control to Pie chart control or all pie chart features will binded to this control
  • json: [data],-> We metioned to pass all Countrywise population data in array format
  • keys: { value: countryNames, -> We are getting the countryNames values from json data that means population data
  • type: 'pie' -> It's to Metion type of chart wanted to generate
  • color: {pattern: -> Combination color will be applied to our chart 
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $.ajax({  
  4.             type: "GET",  
  5.             url: "/Chart/PieChart",  
  6.             data: {},  
  7.             contentType: "application/json; charset=utf-8",  
  8.             dataType: "json",  
  9.             success: function(response) {  
  10.                 successFunc(response);  
  11.             },  
  12.         });  
  13.   
  14.         function successFunc(jsondata) {  
  15.             var data = {};  
  16.             var countryNames = [];  
  17.             jsondata.forEach(function(e) {  
  18.                 countryNames.push(e.CountryName);  
  19.                 data[e.CountryName] = e.CountryPopulation;  
  20.             })  
  21.             var chart = c3.generate({  
  22.                 bindto: '#pieChart',  
  23.                 data: {  
  24.                     json: [data],  
  25.                     keys: {  
  26.                         value: countryNames,  
  27.                     },  
  28.                     type: 'pie'  
  29.                 },  
  30.                 color: {  
  31.                     pattern: ['#1f77b4''#aec7e8''#ff7f0e''#ffbb78''#2ca02c''#98df8a''#d62728''#ff9896''#9467bd''#c5b0d5''#8c564b''#c49c94''#e377c2''#f7b6d2''#7f7f7f''#c7c7c7''#bcbd22''#dbdb8d''#17becf''#9edae5']  
  32.                 },  
  33.             });  
  34.         }  
  35.     });  
  36. </script>  
Now, run your application.
 
Generate Piechart using JavaScript C3 Chart Library and Entity Framework 
Customize Chart
 
We are getting population by country but everything is shown in percentages. Let's convert or display those values as numeric. For that, we will use Pie Chart Label format as below,
  1. pie: {  
  2.     label: {  
  3.         format: function(value, ratio, id) {  
  4.             return value;  
  5.         }  
  6.     }  
  7. }  
Now Run your application,
 
Generate Piechart using JavaScript C3 Chart Library and Entity Framework 
 
Complete View
 
_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 - C3 Charts</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("C3 Charts""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>  
Index.cshtml
  1. @ {  
  2.     ViewBag.Title = "Index";  
  3. } < h2 style = "position:center" > Pie Chart < /h2> < div id = "pieChart" > < /div> < script type = "text/javascript" > $(document).ready(function() {  
  4.     $.ajax({  
  5.         type: "GET",  
  6.         url: "/Chart/PieChart",  
  7.         data: {},  
  8.         contentType: "application/json; charset=utf-8",  
  9.         dataType: "json",  
  10.         success: function(response) {  
  11.             successFunc(response);  
  12.         },  
  13.     });  
  14.   
  15.     function successFunc(jsondata) {  
  16.         var data = {};  
  17.         var countryNames = [];  
  18.         jsondata.forEach(function(e) {  
  19.             countryNames.push(e.CountryName);  
  20.             data[e.CountryName] = e.CountryPopulation;  
  21.         })  
  22.         var chart = c3.generate({  
  23.             bindto: '#pieChart',  
  24.             data: {  
  25.                 json: [data],  
  26.                 keys: {  
  27.                     value: countryNames,  
  28.                 },  
  29.                 type: 'pie'  
  30.             },  
  31.             color: {  
  32.                 pattern: ['#1f77b4''#aec7e8''#ff7f0e''#ffbb78''#2ca02c''#98df8a''#d62728''#ff9896''#9467bd''#c5b0d5''#8c564b''#c49c94''#e377c2''#f7b6d2''#7f7f7f''#c7c7c7''#bcbd22''#dbdb8d''#17becf''#9edae5']  
  33.             },  
  34.             pie: {  
  35.                 label: {  
  36.                     format: function(value, ratio, id) {  
  37.                         return value;  
  38.                     }  
  39.                 }  
  40.             }  
  41.         });  
  42.     }  
  43. }); < /script>  
Controller
  1. using Piechart.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace Piechart.Controllers {  
  8.     public class ChartController: Controller {  
  9.         // GET: Chart  
  10.         public ActionResult Index() {  
  11.             return View();  
  12.         }  
  13.         public ActionResult PieChart() {  
  14.             CSharpCornerEntities entities = new CSharpCornerEntities();  
  15.             return Json(entities.Countries.ToList(), JsonRequestBehavior.AllowGet);  
  16.         }  
  17.     }  
  18. }  
RouteConfig.CS
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7. namespace Piechart {  
  8.     public class RouteConfig {  
  9.         public static void RegisterRoutes(RouteCollection routes) {  
  10.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  11.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
  12.                 controller = "Chart", action = "Index", id = UrlParameter.Optional  
  13.             });  
  14.         }  
  15.     }  
  16. }  
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 Pie 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.


Similar Articles