Pages

Charting with Google Charts in ASP .NET

Monday, February 17, 2014
In this post I am going to show you how to use Google Charts JavaScript library in your ASP .NET web application to visualize your data.  Without adding data manually in JavaScript source I am going to show how to visualize the data sent from the server using JQuery JavaScript library. JQuery help us to communicate with the severe asynchronously without any postbacks.

In this example the chart is created when click on the button. So add following inside your body tag.
The chart is rendered in the div tag
    <input type="button" value="Generate" onclick="GenerateChart()" />
    <div id="piechart" />
Then add following javascript before the end of body tag. Putting javascript below the page contents is a best practice that prevent javascript exceptions. Because when the page execute the javascripts, all the contents in the page are rendered. Also have to use following javascript libraries. Add reference to those javascript libraries correctly.
    <script src="JS/json2.js" type="text/javascript"></script>
    <script src="JS/jquery.1.8.3.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", { packages: ["corechart"] });
        function GenerateChart(){
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                url: 'Default.aspx/GetDataForPie',
                data: '{}',
                success:
                    function (response) {
                        drawVisualization(response.d);
                    }
            });
        }
        function drawVisualization(dataValues) {
            var prod = eval("(" + dataValues + ")");
            
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Column Name');
            data.addColumn('number', 'Column Value');

            data.addRow(['IssuesFixed = ' + prod.IssuesFixed, prod.IssuesFixed]);
            data.addRow(['IssuesNew = ' + prod.IssuesNew, prod.IssuesNew]);
            data.addRow(['IssuesWIP = ' + prod.IssuesWIP, prod.IssuesWIP]);
            data.addRow(['IssuesAccepted = ' + prod.IssuesAccepted, prod.IssuesAccepted]);
            data.addRow(['IssuesCancelled = ' + prod.IssuesCancelled, prod.IssuesCancelled]);
            data.addRow(['IssuesClarification = ' + prod.IssuesClarification, prod.IssuesClarification]);
            data.addRow(['IssuesOnHold = ' +prod.IssuesOnHold, prod.IssuesOnHold]);
            data.addRow(['IssuesClarified = ' +prod.IssuesClarified, prod.IssuesClarified]);
            data.addRow(['IssuesClosed = ' +prod.IssuesClosed, prod.IssuesClosed]);

            var chart = new google.visualization.PieChart(document.getElementById('piechart'));
                
            var options = {
                width: 400,
                height: 300,
                title: prod.ProjectID,
                sliceVisibilityThreshold: 0,
                is3D: true,
                chartArea: { left: 0, top: 10, width: "100%" },
                legend: 'bottom'
            };
            chart.draw(data, options);
        }
    </script>
When clicks on the button Ajax call is made using JQuery and call GetDataForPie method in your code behind and when server response is success it will create chart using returned JSON string from the server.
Add following references in your code behind.
   using System.Web.Services;
   using System.Web.Script.Serialization;
Then add following method.
   class MyObject
   {
            public int IssuesNew { get; set; }
            public int IssuesWIP { get; set; }
            public int IssuesFixed { get; set; }
            public int IssuesAccepted { get; set; }
            public int IssuesCancelled { get; set; }
            public int IssuesClarification { get; set; }
            public int IssuesOnHold { get; set; }
            public int IssuesClarified { get; set; }
            public int IssuesClosed { get; set; }
   }
   [WebMethod]
   public static string GetDataForPie()
   {
      try
      {
          MyObject obj = new MyObject()
          {
              IssuesNew = 12,
              IssuesWIP = 5,
              IssuesFixed = 20,
              IssuesAccepted = 15,
              IssuesCancelled=8,
              IssuesClarification=2,
              IssuesOnHold=10,
              IssuesClarified=4,
              IssuesClosed=25
           };
           JavaScriptSerializer serializer = new JavaScriptSerializer();
           string JSON = serializer.Serialize(obj).ToString();
           return JSON;
       }
       catch (Exception e)
       {
           throw;
        }   
   }
Above method convert the MyObject object into JSON string and return to the client. If the data is returned successfully then 'drawVisualization' javascript method is called with returned JSON string as input parameter.
In  'drawVisualization' method first line convert the JSON string into JSON object and next few lines create a data table and add values to that data table using the JSON object. Then we define the page element that contain the chart. Also we can define some charting options options. Then the chart is down using data table and chart options.
Also you can get data from database to you code behind and send that to client as the above JSON string.
Read more ...