Dec 20

Google Visualization Charts using jQuery and ASP.NET MVC – Part 2(Pie & Donut Chart)

Google Visualization Charts using jQuery and ASP.NET MVC – Part 2(Pie & Donut Chart)

1. Introduction

Chart is also called as graph and it is graphical representation of data. Chart can usually be read more quickly than the row data. Chart is the greatest and simplest way to express data to user or management persons. Charts are very common in all type of business requirement. In one of my assignment there were the functionality of organization chart display. I googled and explored various approaches to find the solution and found interesting article on google i.e. Google Charts. The google chart tools are powerful and easy to use. Google also provides different type of rich gallery of interactive charts and data tools.

In previous article we discussed Organization Chart and Bar and Column Chars using google visualization chart. In this article I will explain how google visualization charting tool useful for displaying Pie and Donut chart using ASP.NET MVC.

Click here to view basic concept of Charts. The Overview section will explain The details about various parts or concepts of a chart.

2. Overview

In my careers starting days with ASP.NET, I remember we used different type of third party control to implement chart functionality in applications. But now using different open source library provides inbuilt support for different Chart in a very simpler fashion. The Google Charts shows how we can display Pie and Donut Chart in very simpler manner .
Google charts provides a perfect way to visualize data on your website. The google chart gallery provides number of ready-to-use chart types. The most common way to use Google Charts is with simple JavaScript that you embed in your web page. You load some Google Chart libraries, list the data to be charted, select options to customize your chart, and finally create a chart object with an id that you choose. Then, later in the web page, you create a <div> with that id to display the Google Chart. Google Charts are rendered using HTML5/SVG technology to provide cross-browser compatibility and cross platform portability to iPhones, iPads and Android.

All chart types are populated with data using the DataTable class, making it easy to switch between chart types as you experiment to find the ideal appearance. The DataTable provides methods for sorting, modifying, and filtering data, and can be populated directly from your web page, a database, or any data provider supporting the Chart Tools Datasource protocol.
It uses below simple steps.
1.       Load AJAX API library from Google Chart website
2.       Load the Visualization API and the required package.
3.       Set a callback to run when the Google Visualization API is loaded.
4.       Callback that creates and populates a data table, instantiates the required chart, passes in the data and draws it.
5.       Create the data table.
6.       Set chart options
7.       Instantiate and draw our chart, passing in some options.
8.       Create Div that will hold the required chart

3. Practical Implementation

There are multiple ways to achieve charting functionality. You can create chart using arrays, database query or using xml data. Below example explains how to create chart using json arrays result.
Here we need to use below properties to display 3D and Donut charts options
For 3D-Pie Chart
is3D: true
For Donut Chart
pieHole: 0.6
Now First you should,
Download the loader.js and jsapi.js javascript library to your project or you give reference of this library in your ASP.NET MVC page.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
Step 1: Download library to your projects script folder and create bundle in BundleConfig.cs file.
bundles.Add(new ScriptBundle(“~/bundles/googleChart”).Include(
                 “~/Scripts/loader.js”, “~/Scripts/jsapi.js”
                        ));
 
Step 2: Create Razor engine view page and refer the above bundle file.
@{
              ViewBag.Title = “Google Visualization Chart”;
}
@Scripts.Render(“~/bundles/googleChart”)
<h2>Pie Chart Display</h2>
<div style=”padding-top:50px;“></div>
<div id=”pieChartDiv” style=”width: 900px; height: 500px;“></div>
<h2>3D-Pie Chart Display</h2>
<div style=”padding-top:50px;“></div>
<div id=”3dPieChartDiv” style=”width: 900px; height: 500px;“></div>
<h2>Donut Chart Display</h2>
<div style=”padding-top:50px;“></div>
<div id=”donutChartDiv” style=”width: 900px; height: 500px;“></div>
Step 3: Create or write javascript and refer on page.
<script type=”text/javascript”>
     google.charts.load(‘current’, { packages: [‘corechart’] });
     google.charts.setOnLoadCallback(drawPieChartAjax);
     var myjson =
     functiondrawPieChartAjax() {
         $.ajax({
             type: “GET”,
             contentType: “application/json; charset=utf-8”,
             url: “PieChart/PieChart”,
             data: “{}”,
             dataType: “json”,
             cache: true,
             success: function (result) {
                 myjson = result;
                 drawPieChart(result);
             },
             error: function (result) {
                 alert(“Error”);
             }
         });
     }
     functiondrawPieChart(jsonResult) {
         var series = [];
         varseriesData = [];
         var items = [];
         var rows = [];
         series.push(myjson.SeriesName);
         series.push();
         $.each(myjson.Series, function (keySeries, series) {
             seriesData.push(series.name);
             seriesData.push(series.y);
             items.push(seriesData);
             seriesData = [];
         });
         //final table
         rows.push(series);
         $.each(items, function (j, val) {
             rows.push(val);
         });
        
         var data = newgoogle.visualization.arrayToDataTable(rows);
         //var data = new google.visualization.arrayToDataTable([
         //  [‘Browser’, ‘Percentage’],
         //  [‘Microsoft Internet Explorer’, 56.33],
         //  [‘Chrome’, 24.03],
         //  [‘Firefox’, 10.38],
         //  [‘Safari’, 4.77],
         //  [‘Opera’, 0.91],
         //  [‘Proprietary or Undetectable’, 0.02]
         //]);
         // To Display  chart
         varoptionsPieChart = {
             title: jsonResult.Title
         };
         chart = newgoogle.visualization.PieChart(document.getElementById(‘pieChartDiv’));
         chart.draw(data, optionsPieChart);
         // To Display 3d chart
         varoptions3dPieChart = {
             title: jsonResult.Title,
             is3D: true
         };
         chart = newgoogle.visualization.PieChart(document.getElementById(‘3dPieChartDiv’));
         chart.draw(data, options3dPieChart);
         // To Display donut chart
         varoptionsDonutChart = {
             title: jsonResult.Title,
             pieHole: 0.6
         };
         chart = newgoogle.visualization.PieChart(document.getElementById(‘donutChartDiv’));
         chart.draw(data, optionsDonutChart);
     }
</script>
 
Step 4: Create appropriate model to display data. We already discussed this model in my previous post. So utilizing same code here as well.
    public class PieChartSeriesModel<T>
    {
        public string name { get; set; }
        public T y { get; set; }
        public bool sliced { get; set; }
        public bool selected { get; set; }
    }
    public class PieChartModel<T>
    {
        public string Title { get; set; }
        public string Tooltip { get; set; }
        public stringSeriesName { get; set; }
        public ICollection<PieChartSeriesModel<T>> Series { get; set; }
    }
 
Step 5: Create controller file and create action do display result. We already discussed this controller code in my previous post. So utilizing same code here as well.

public ActionResult Index()
        {
            return View();
        }
        public JsonResultPieChart()
        {
            varpieChartModel = new PieChartModel<double>
            {
                Title = “Browser market shares January, 2015 to May, 2015”,
                Tooltip = “{series.name}: <b>{point.percentage:.1f}%</b>”,
                SeriesName = “Browser:”,
                Series = new List<PieChartSeriesModel<double>> {
                    new PieChartSeriesModel<double>{name = “Microsoft Internet Explorer”, y= 56.33},
                    new PieChartSeriesModel<double>{name = “Chrome”, y= 24.03, selected=true, sliced=true},
                    new PieChartSeriesModel<double>{name = “Firefox”, y= 10.38},
                    new PieChartSeriesModel<double>{name = “Safari”, y= 4.77},
                    new PieChartSeriesModel<double>{name = “Opera”, y= 0.91},
                    new PieChartSeriesModel<double>{name = “Proprietary or Undetectable”, y= 0.2},
                }
            };
            returnJson(pieChartModel, JsonRequestBehavior.AllowGet);
        }
Step 6: Now, run the application to display Pie, 3D-Pie and Donut Chart respectively.

Pie Chart

 
 

3D-Pie Chart

 
 

Donut Chart

 
 
I hope you enjoyed the sample code that I provided. I would suggest you to play something around the code and theme.

4. Summary

Using Google Visualization Chart tool, it is very easy to show chart in your ASP.NET MVC application. In this article, I showed you how to create Pie and Donut Chart in ASP.NET MVC. Hopefully you will enjoy this article too. In my next blog post article, I will explain how Google Visualization Chart tools are useful to display Other Charts in ASP.NET MVC.

5. Download Code

 

Click here to download the source code of this assignment.

Leave a Reply