Google Charts, ASP.NET, jQuery, AJAX – Quick & Easy

What to do when there is a requirement in your application to make a graphical representation of some statistical data? Well, there are a lot of controls you can use, depending on your needs.

In this post, I’ll show you how to quickly and easily introduce Google charts to your ASP.NET application, getting something like this as a result:

GoogleCharts

Also, I’ll be using jQuery and AJAX for fetching data, although they are not necessary, of course.

First of all, let’s define the data we want to show in the chart. This is really basic example, so my class looks something like this:

public class Data
{
    public string ColumnName = "";
    public int Value = 0;

    public Data(string columnName, int value)
    {
        ColumnName = columnName;
        Value = value;
    }
}

This is really all we need to display the chart: data caption and value.

Next, here is the method for getting the data from the server:

[WebMethod]
public static List<Data> GetData()
{
    List<Data> dataList = new List<Data>();

    dataList.Add(new Data("Column 1", 100));
    dataList.Add(new Data("Column 2", 200));
    dataList.Add(new Data("Column 3", 300));
    dataList.Add(new Data("Column 4", 400));

    return dataList;       
}

This is a web method, since I’ll make AJAX call from the client to get JSON object containing data to be displayed. Bear in mind that there is no need for serializing to JSON string – just make the method return the object, or in this case – list of objects.

As for the client script, let’s take a look at the AJAX method for fetching the data from the server:

  
$(document).ready(function() {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: 'Default.aspx/GetData',
        data: '{}',
        success:
            function(response) {
                drawVisualization(response.d);
            }
        });
    })
})

Nothing new here – just defining which server method to invoke and what to do when the data is received.

We need to define where the chart will be drawn:

  
<div id="visualization" style="width: 600px; height: 400px;"></div>

To display the Google chart, we must load three libraries: the Google JSAPI API, the Google Visualization library and the library for the chart itself.

First of all, Google JSAPI API:

  
<script type="text/javascript" src="//www.google.com/jsapi"></script>

Next, load the Google Visualization and chart libraries:

  
<script type="text/javascript">
    google.load('visualization', '1', { packages: ['corechart'] });
</script>

Note:
- ‘visualization’ – loads the google.visualization library, which defines all the core utility classes and functions.
- ’1′ – visualization version to load (’1′ is current production version).
- { packages: ['corechart'] } – here we can define the list of all Google chart libraries needed. The ‘corechart’ library contains most basic charts, including pie chart, which we use in this example.

Finally, here is the function that will actually draw the chart:

  
function drawVisualization(dataValues) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Column Name');
    data.addColumn('number', 'Column Value');

    for (var i = 0; i < dataValues.length; i++) {
        data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
    }

    new google.visualization.PieChart(document.getElementById('visualization')).
        draw(data, { title: "Google Charts Example" });          
}

The code is self-explanatory: the DataTable is initialized, the columns are added to it, and then the data is entered. Finally, new PieChart is initialized and its draw method is invoked.

The whole example:
cs:

 
using System;
using System.Collections.Generic;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    [WebMethod]
    public static List<Data> GetData()
    {
        List<Data> dataList = new List<Data>();

        dataList.Add(new Data("Column 1", 100));
        dataList.Add(new Data("Column 2", 200));
        dataList.Add(new Data("Column 3", 300));
        dataList.Add(new Data("Column 4", 400));

        return dataList;       
    }
}

public class Data
{
    public string ColumnName = "";
    public int Value = 0;

    public Data(string columnName, int value)
    {
        ColumnName = columnName;
        Value = value;
    }
}

aspx:

 
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load('visualization', '1', { packages: ['corechart'] });
    </script>
    <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                url: 'Default.aspx/GetData',
                data: '{}',
                success:
                    function(response) {
                        drawVisualization(response.d);
                    }

            });
        })

        function drawVisualization(dataValues) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Column Name');
            data.addColumn('number', 'Column Value');

            for (var i = 0; i < dataValues.length; i++) {
                data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
            }

            new google.visualization.PieChart(document.getElementById('visualization')).
                draw(data, { title: "Google Charts Example" });          
        }

        
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="visualization" style="width: 600px; height: 400px;"></div>
    </form>
</body>
</html>

Google charts are easy to implement and highly customizable. I will be writing more about different types of charts and how to customize them, in my future posts.

6 comments

  1. Wayne Atherton

    Hi there,

    I like your presentation skills – very clear. I do have one question, which i’m hoping you can assist with. Every example i’ve come across seems to use hard coded values, i need to collect the data from SQL server. Do you have an example of this please?

  2. Bhanu Prakash Inturi

    Hi, very nice article explained clearly regarding charts, have one question is it possible for us, to implement Bar Charts, Line Charts etc.. instead of Pie Chart

    Thanks
    Bhanu

    • swaroop

      new google.visualization.PieChart(document.getElementById(‘visualization’)).
      draw(data, { title: “Total Accounts” });
      replace of PieChart to BarChart, LineChart.

  3. Jamel

    great article, spent 2 days trying to get asp chart control to work, but I get bugged by all the issues at dev and at upload to prod server (routing, temp folder, error 500…) it is just one error after the other to the point that I have no more faith in the asp chart tool.
    I just gave up and rather learn something that will work.
    This look good, and sounds very easy where I don’t have to deal with server and routing.

    Thanks again.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>