ASP.NET MVC 5 - Generate Bar Chart Using JavaScript C3 Chart Library And Entity Framework

In this article, I will demonstrate how to generate a bar chart using C3 Chart JavaScript Library to view the population by gender from a database using Entity Framework in ASP.NET MVC5. Let's move forward.
  • 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 a database with the list of the 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 "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,  
  9. (  
  10.    [Id] ASC  
  12. ON [PRIMARY]  
  13. GO  
And now, add a few dummy values to view in the pie chart. I have added some rows as shown below,
To add these dummy data values of the countrywise population, 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-11-05T02: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-10-05T02: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-09-05T02: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-08-05T02: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-07-05T02: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-06-05T02: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'2017-11-05T02: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'2017-10-05T02: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'2017-09-05T02: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'2017-08-05T02: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'2017-06-05T02: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 "Barchart".
  • 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 "ChartController". 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 MyPrevious Article.
Generate a Chart Controller 
Now, write a 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 "BarChart" action to fetch the data from the 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 Barchart.Controllers {  
  8.     public class ChartController: Controller {  
  9.         // GET: Chart  
  10.         public ActionResult Index() {  
  11.             return View();  
  12.         }  
  13.         public ActionResult BarChart() {  
  14.             CSharpCornerEntities1 entities = new CSharpCornerEntities1();  
  15.             return Json(entities.Populations.ToList(), JsonRequestBehavior.AllowGet);  
  16.         }  
  17.     }  
  18. }  
In View, add a Controller which will act as a bar chart in our application. For that, I have added one div with the name of Barchart. 
  1. <div id="Barchart"></div>  
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: "/Chart/BarChart",  
  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 chart as below,
  • c3.generate({ -> This is the predefined keyword c3 charts to generate charts on respective controls
  • bindto: '#Barchart', -> Changing our div control to Bar chart control or all bar chart features will bind to this control
  • json: jsondata,-> We metioned to pass all Genderwise population data in json format
  • keys: { value: Male, Female, Others-> We are getting values of males, females, and others from json data; that means population data
  • type: 'bar' -> It's to mention the type of chart wanted to generate
  • color: {pattern: -> Combination color will be applied to our chart
  1. function successFunc(jsondata) {  
  2.     var chart = c3.generate({  
  3.         bindto: '#Barchart',  
  4.         data: {  
  5.             json: jsondata,  
  6.             keys: {  
  7.                 value: ['Male''Female''Others'],  
  8.             },  
  9.             columns: ['Male''Female''Others'],  
  10.             type: 'bar',  
  11.         },  
  12.         color: {  
  13.             pattern: ['#1f77b4''#aec7e8''#ff7f0e''#ffbb78''#2ca02c''#98df8a''#d62728''#ff9896''#9467bd''#c5b0d5''#8c564b''#c49c94''#e377c2''#f7b6d2''#7f7f7f''#c7c7c7''#bcbd22''#dbdb8d''#17becf''#9edae5']  
  14.         },  
  15.     });  
  16. }  
Now Run your application,
In the result, we can see that we got the chart as per the data. Now let's do some customization on this chart.
Customize Chart
We have many records for a year, so now we will try to show the record in a single bar. We achieve that using a stacked bar chart. We have to use the groups and need to mention the columns to merge in a single bar.
  1. groups: [  
  2.    ['Male''Female','Others']  
  3. ]  
Now run your application,
The grouping will happen by mentioning the column name, if you want to do two column groupings, you can remove the respective column from that column array. We will do more customization on the bar chart in the next article.
Complete View
  1. @ {  
  2.     ViewBag.Title = "Index";  
  3. } < br / > < div id = "Barchart" > < /div> < script type = "text/javascript" > $(document).ready(function() {  
  4.     $.ajax({  
  5.         type: "GET",  
  6.         url: "/Chart/BarChart",  
  7.         data: {},  
  8.         contentType: "application/json; charset=utf-8",  
  9.         dataType: "json",  
  10.         success: function(response) {  
  11.             successFunc(response);  
  12.         },  
  13.     });  
  15.     function successFunc(jsondata) {  
  16.         var chart = c3.generate({  
  17.             bindto: '#Barchart',  
  18.             data: {  
  19.                 json: jsondata,  
  20.                 keys: {  
  21.                     value: ['Male''Female''Others'],  
  22.                 },  
  23.                 columns: ['Male''Female''Others'],  
  24.                 type: 'bar',  
  25.                 groups: [  
  26.                     ['Male''Female''Others']  
  27.                 ]  
  28.             },  
  29.             color: {  
  30.                 pattern: ['#1f77b4''#aec7e8''#ff7f0e''#ffbb78''#2ca02c''#98df8a''#d62728''#ff9896''#9467bd''#c5b0d5''#8c564b''#c49c94''#e377c2''#f7b6d2''#7f7f7f''#c7c7c7''#bcbd22''#dbdb8d''#17becf''#9edae5']  
  31.             },  
  32.         });  
  33.     }  
  34. }); < /script>  
  1. using Piechart.Models;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4. namespace Barchart.Controllers {  
  5.     public class ChartController: Controller {  
  6.         // GET: Chart  
  7.         public ActionResult Index() {  
  8.             return View();  
  9.         }  
  10.         public ActionResult BarChart() {  
  11.             CSharpCornerEntities1 entities = new CSharpCornerEntities1();  
  12.             return Json(entities.Populations.ToList(), JsonRequestBehavior.AllowGet);  
  13.         }  
  14.     }  
  15. }  
Refer to the attached project for reference and I did attach the demonstrated project without a package due to the size limit.
In this article, we have seen how to generate a C3 Bar 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