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.
Execute the below query to create a table with the above design.
- CREATE TABLE [dbo].[Country](
- [CountryID] [bigint] IDENTITY(1,1) NOT NULL,
- [CountryName] [nvarchar](250) NULL,
- [CountryPopulation] [float] NULL,
- CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED
- (
- [CountryID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- 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.
- SET IDENTITY_INSERT [dbo].[Country] ON
- GO
- INSERT [dbo].[Country] ([CountryID], [CountryName], [CountryPopulation]) VALUES (1, N'India', 300)
- GO
- INSERT [dbo].[Country] ([CountryID], [CountryName], [CountryPopulation]) VALUES (2, N'UK', 200)
- GO
- INSERT [dbo].[Country] ([CountryID], [CountryName], [CountryPopulation]) VALUES (3, N'US', 100)
- GO
- SET IDENTITY_INSERT [dbo].[Country] OFF
- 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 2013.
- Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it "Piechart".
- 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 Step1 and Step2 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 "Country" 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 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
Install C3 Chart
Browse the C3 chart and install it.
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.
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).
- <link href="~/Content/c3.css" rel="stylesheet" />
- <link href="~/Content/Site.css" rel="stylesheet" />
- <link href="~/Content/bootstrap.css" rel="stylesheet" />
- <script src="~/Scripts/c3.min.js"></script>
- <script src="~/Scripts/d3.min.js"></script>
- <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.
- using Piechart.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace Piechart.Controllers {
- public class ChartController: Controller {
-
- public ActionResult Index() {
- return View();
- }
- public ActionResult PieChart() {
- CSharpCornerEntities entities = new CSharpCornerEntities();
- return Json(entities.Countries.ToList(), JsonRequestBehavior.AllowGet);
- }
- }
- }
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.
- <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.
- <script type="text/javascript">
- $(document).ready(function() {
- $.ajax({
- type: "GET",
- url: "/Chart/PieChart",
- data: {},
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function(response) {
- successFunc(response);
- },
- });
-
- function successFunc(jsondata) {
- var data = {};
- var countryNames = [];
- jsondata.forEach(function(e) {
- countryNames.push(e.CountryName);
- data[e.CountryName] = e.CountryPopulation;
- })
- var chart = c3.generate({
- bindto: '#pieChart',
- data: {
- json: [data],
- keys: {
- value: countryNames,
- },
- type: 'pie'
- },
- color: {
- pattern: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']
- },
- });
- }
- });
- </script>
Now, run your application.
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,
- pie: {
- label: {
- format: function(value, ratio, id) {
- return value;
- }
- }
- }
Now Run your application,
Complete View
_Layout.cshtml
- <!DOCTYPE html>
- <html>
-
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - C3 Charts</title>
- <link href="~/Content/c3.css" rel="stylesheet" />
- <link href="~/Content/Site.css" rel="stylesheet" />
- <link href="~/Content/bootstrap.css" rel="stylesheet" />
- <script src="~/Scripts/c3.min.js"></script>
- <script src="~/Scripts/d3.min.js"></script>
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- </head>
-
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button> @Html.ActionLink("C3 Charts", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- </ul>
- </div>
- </div>
- </div>
- <div class="container body-content"> @RenderBody()
- <hr />
- <footer>
- <p>© @DateTime.Now.Year - My ASP.NET Application</p>
- </footer>
- </div>
- </body>
-
- </html>
Index.cshtml
- @ {
- ViewBag.Title = "Index";
- } < h2 style = "position:center" > Pie Chart < /h2> < div id = "pieChart" > < /div> < script type = "text/javascript" > $(document).ready(function() {
- $.ajax({
- type: "GET",
- url: "/Chart/PieChart",
- data: {},
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function(response) {
- successFunc(response);
- },
- });
-
- function successFunc(jsondata) {
- var data = {};
- var countryNames = [];
- jsondata.forEach(function(e) {
- countryNames.push(e.CountryName);
- data[e.CountryName] = e.CountryPopulation;
- })
- var chart = c3.generate({
- bindto: '#pieChart',
- data: {
- json: [data],
- keys: {
- value: countryNames,
- },
- type: 'pie'
- },
- color: {
- pattern: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']
- },
- pie: {
- label: {
- format: function(value, ratio, id) {
- return value;
- }
- }
- }
- });
- }
- }); < /script>
- using Piechart.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace Piechart.Controllers {
- public class ChartController: Controller {
-
- public ActionResult Index() {
- return View();
- }
- public ActionResult PieChart() {
- CSharpCornerEntities entities = new CSharpCornerEntities();
- return Json(entities.Countries.ToList(), JsonRequestBehavior.AllowGet);
- }
- }
- }
RouteConfig.CS
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace Piechart {
- public class RouteConfig {
- public static void RegisterRoutes(RouteCollection routes) {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {
- controller = "Chart", action = "Index", id = UrlParameter.Optional
- });
- }
- }
- }
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.