ASP.NET Webform - Google Charts API Integration

Graphs/Charts are an important form of representing data which help in making meaningful reports for analytical purposes. This eventually helps stakeholders to make a better decision. While Google charts API is one of the key APIs for graphs/charts integration in many development platforms; i.e., ASP.NET MVC, ASP.NET webform, PHP, and many more, I will be mainly focusing on Google charts API integration in ASP.NET Webform in particular.

So, today, I shall be demonstrating the integration of Google charts API in ASP.NET Webform. Google charts API is simple to use and provides a variety of options for customization of graphical chart reports for better analytical purposes.


Prerequisites

Following are some prerequisites before you proceed further in this tutorial:

  1. Knowledge of Google charts API.
  2. Knowledge of classic ASP.NET webform.
  3. Knowledge of WebMethod attribute.
  4. Knowledge of HTML.
  5. Knowledge of JavaScript.
  6. Knowledge of AJAX.
  7. Knowledge of CSS.
  8. Knowledge of Bootstrap.
  9. Knowledge of C# programming.
  10. Knowledge of C# LINQ.
  11. Knowledge of jQuery.

You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is developed in Microsoft Visual Studio 2015 Enterprise. I am using SalesOrderDetail table extract from Adventure Works Sample Database.

Let's begin now.

Step 1

Create a new Webform web application project and name it "GoogleGraphsWebform".

Step 2

Before you move any further in this tutorial, you need to do the following configuration in "App_Start\RouteConfig.cs" file for asp.net webform "WebMethod" attribute to work. If you do not do the configuration as below then your "WebMethod" attribute will not work and your Ajax back-end method will not be hit when it is called via javascript. So, replace the following code in "App_Start\RouteConfig.cs" file:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web;  
  4. using System.Web.Routing;  
  5. using Microsoft.AspNet.FriendlyUrls;  
  6.   
  7. namespace GoogleGraphsWebform  
  8. {  
  9.     public static class RouteConfig  
  10.     {  
  11.         public static void RegisterRoutes(RouteCollection routes)  
  12.         {  
  13.             var settings = new FriendlyUrlSettings();  
  14.             settings.AutoRedirectMode = RedirectMode.Off; // RedirectMode.Permanent  
  15.             routes.EnableFriendlyUrls(settings);  
  16.         }  
  17.     }  

In the above code, I have simply turned off the auto redirection mode. By default, it is set to "Permanent" mode. For our Ajax WebMethod to work we need to change the "AutoRedirectMode" to "Off".

Step 3

Open "App_Start\BundleConfig.cs" file and replace the following code in it:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Optimization;  
  6. using System.Web.UI;  
  7.   
  8. namespace GoogleGraphsWebform  
  9. {  
  10.     public class BundleConfig  
  11.     {  
  12.         // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkID=303951  
  13.         public static void RegisterBundles(BundleCollection bundles)  
  14.         {  
  15.             bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(  
  16.                             "~/Scripts/WebForms/WebForms.js",  
  17.                             "~/Scripts/WebForms/WebUIValidation.js",  
  18.                             "~/Scripts/WebForms/MenuStandards.js",  
  19.                             "~/Scripts/WebForms/Focus.js",  
  20.                             "~/Scripts/WebForms/GridView.js",  
  21.                             "~/Scripts/WebForms/DetailsView.js",  
  22.                             "~/Scripts/WebForms/TreeView.js",  
  23.                             "~/Scripts/WebForms/WebParts.js"));  
  24.   
  25.             // Order is very important for these files to work, they have explicit dependencies  
  26.             bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include(  
  27.                     "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js",  
  28.                     "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js",  
  29.                     "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js",  
  30.                     "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js"));  
  31.   
  32.             // Use the Development version of Modernizr to develop with and learn from. Then, when you’re  
  33.             // ready for production, use the build tool at http://modernizr.com to pick only the tests you need  
  34.             bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(  
  35.                             "~/Scripts/modernizr-*"));  
  36.   
  37.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  38.                         "~/Scripts/jquery-{version}.js"));  
  39.   
  40.             bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  41.                         "~/Scripts/jquery.validate*"));  
  42.   
  43.             bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(  
  44.                       "~/Scripts/bootstrap.js",  
  45.                       "~/Scripts/respond.js"));  
  46.   
  47.             ScriptManager.ScriptResourceMapping.AddDefinition(  
  48.                 "respond",  
  49.                 new ScriptResourceDefinition  
  50.                 {  
  51.                     Path = "~/Scripts/respond.min.js",  
  52.                     DebugPath = "~/Scripts/respond.js",  
  53.                 });  
  54.         }  
  55.     }  

In the above code, I have simply added JQuery, JQuery validation and Bootstrap libraries references in the bundle file.

Step 4

Now, open "App_Start\Site.Master" file and replace the following code in it:

  1. <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="GoogleGraphsWebform.SiteMaster" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html lang="en">  
  6. <head runat="server">  
  7.     <meta charset="utf-8" />  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
  9.     <title><%: Page.Title %></title>  
  10.   
  11.     <asp:PlaceHolder runat="server">  
  12.         <%: Scripts.Render("~/bundles/modernizr") %>  
  13.         <%: Scripts.Render("~/bundles/jquery") %>  
  14.     </asp:PlaceHolder>  
  15.     <webopt:bundlereference runat="server" path="~/Content/css" />  
  16.     <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />  
  17.   
  18.     <!-- Font Awesome -->  
  19.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
  20.   
  21.     <!-- Graphs -->  
  22.     <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
  23.     <script src="Scripts/custom-graph.js" type="text/javascript"></script>  
  24.   
  25. </head>  
  26. <body>  
  27.     <form runat="server">  
  28.         <asp:ScriptManager runat="server">  
  29.             <Scripts>  
  30.                 <%--To learn more about bundling scripts in ScriptManager see http://go.microsoft.com/fwlink/?LinkID=301884 --%>  
  31.                 <%--Framework Scripts--%>  
  32.                 <asp:ScriptReference Name="MsAjaxBundle" />  
  33. <%--                <asp:ScriptReference Name="jquery" />--%>  
  34.                 <asp:ScriptReference Name="bootstrap" />  
  35.                 <asp:ScriptReference Name="respond" />  
  36.                 <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />  
  37.                 <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />  
  38.                 <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />  
  39.                 <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />  
  40.                 <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />  
  41.                 <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />  
  42.                 <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />  
  43.                 <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />  
  44.                 <asp:ScriptReference Name="WebFormsBundle" />  
  45.                 <%--Site Scripts--%>  
  46.             </Scripts>  
  47.         </asp:ScriptManager>  
  48.   
  49.         <div class="navbar navbar-inverse navbar-fixed-top">  
  50.             <div class="container">  
  51.                 <div class="navbar-header">  
  52.                     <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  53.                         <span class="icon-bar"></span>  
  54.                         <span class="icon-bar"></span>  
  55.                         <span class="icon-bar"></span>  
  56.                     </button>  
  57.                 </div>  
  58.             </div>  
  59.         </div>  
  60.   
  61.         <div class="container body-content">  
  62.             <asp:ContentPlaceHolder ID="MainContent" runat="server">  
  63.             </asp:ContentPlaceHolder>  
  64.             <hr />  
  65.             <footer>  
  66.                 <center>  
  67.                     <p><strong>Copyright © <%: DateTime.Now.Year %> - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
  68.                 </center>  
  69.             </footer>  
  70.         </div>  
  71.     </form>  
  72. </body>  
  73. </html> 

In the above code, I have simply created the basic layout structure of this web project and I have also added a reference to the Google charts API.

Step 5

Create a new "Models\SalesOrderDetail.cs" & "Models\GraphData.cs" file and replace following code in it:

Models\SalesOrderDetail.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace GoogleGraphsWebform.Models  
  7. {  
  8.     public class SalesOrderDetail  
  9.     {  
  10.         public int Sr { getset; }  
  11.         public string OrderTrackNumber { getset; }  
  12.         public int Quantity { getset; }  
  13.         public string ProductName { getset; }  
  14.         public string SpecialOffer { getset; }  
  15.         public double UnitPrice { getset; }  
  16.         public double UnitPriceDiscount { getset; }  
  17.     }  

In the above code, I have simply created object class which will map the data from text file into main memory as object.

Models\GraphData.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace GoogleGraphsWebform.Models  
  7. {  
  8.     public class GraphData  
  9.     {  
  10.         public int Quantity { getset; }  
  11.         public string ProductName { getset; }  
  12.         public double UnitPrice { getset; }  
  13.     }  

In the above code, I have simply created a graph data model which will be passed to the Google charts API via javascript.

Step 6

Now open"Default.aspx\Default.aspx.cs" file and replace the following code in it:

  1. using GoogleGraphsWebform.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Reflection;  
  7. using System.Web;  
  8. using System.Web.Script.Services;  
  9. using System.Web.Services;  
  10. using System.Web.UI;  
  11. using System.Web.UI.WebControls;  
  12.   
  13. namespace GoogleGraphsWebform  
  14. {  
  15.     public partial class _Default : Page  
  16.     {  
  17.         #region Page Load event  
  18.   
  19.         protected void Page_Load(object sender, EventArgs e)  
  20.         {  
  21.             try  
  22.             {  
  23.                 // info.  
  24.                 Console.Write("test");  
  25.             }  
  26.             catch (Exception ex)  
  27.             {  
  28.                 // info.  
  29.                 Console.Write(ex);  
  30.             }  
  31.         }  
  32.  
  33.         #endregion  
  34.  
  35.         #region Get data method.  
  36.   
  37.         /// <summary>  
  38.         /// GET: Default.aspx/GetData  
  39.         /// </summary>  
  40.         /// <returns>Return data</returns>  
  41.         [WebMethod]  
  42.         [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]  
  43.         public static List<GraphData> GetData()  
  44.         {  
  45.             // Initialization.  
  46.             List<GraphData> result = new List<GraphData>();  
  47.   
  48.             try  
  49.             {  
  50.                 // Loading.  
  51.                 List<SalesOrderDetail> data = _Default.LoadData();  
  52.   
  53.                 // Setting.  
  54.                 var graphData = data.GroupBy(p => new  
  55.                 {  
  56.                     p.ProductName,  
  57.                     p.Quantity,  
  58.                     p.UnitPrice  
  59.                 })  
  60.                                     .Select(g => new  
  61.                                     {  
  62.                                         g.Key.ProductName,  
  63.                                         g.Key.Quantity,  
  64.                                         g.Key.UnitPrice  
  65.                                     }).OrderByDescending(q => q.Quantity).ToList();  
  66.   
  67.                 // Top 10  
  68.                 graphData = graphData.Take(10).Select(p => p).ToList();  
  69.   
  70.                 // Loading.  
  71.                 result = graphData.Select(p => new GraphData  
  72.                 {  
  73.                     ProductName = p.ProductName,  
  74.                     Quantity = p.Quantity,  
  75.                     UnitPrice = p.UnitPrice  
  76.                 }).ToList();  
  77.             }  
  78.             catch (Exception ex)  
  79.             {  
  80.                 // Info  
  81.                 Console.Write(ex);  
  82.             }  
  83.   
  84.             // Return info.  
  85.             return result;  
  86.         }  
  87.  
  88.         #endregion  
  89.  
  90.         #region Helpers  
  91.  
  92.         #region Load Data  
  93.   
  94.         /// <summary>  
  95.         /// Load data method.  
  96.         /// </summary>  
  97.         /// <returns>Returns - Data</returns>  
  98.         private static List<SalesOrderDetail> LoadData()  
  99.         {  
  100.             // Initialization.  
  101.             List<SalesOrderDetail> lst = new List<SalesOrderDetail>();  
  102.   
  103.             try  
  104.             {  
  105.                 // Initialization.  
  106.                 string line = string.Empty;  
  107.                 string srcFilePath = "Content/files/SalesOrderDetail.txt";  
  108.                 var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);  
  109.                 var fullPath = Path.Combine(rootPath, srcFilePath);  
  110.                 string filePath = new Uri(fullPath).LocalPath;  
  111.                 StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));  
  112.   
  113.                 // Read file.  
  114.                 while ((line = sr.ReadLine()) != null)  
  115.                 {  
  116.                     // Initialization.  
  117.                     SalesOrderDetail infoObj = new SalesOrderDetail();  
  118.                     string[] info = line.Split(',');  
  119.   
  120.                     // Setting.  
  121.                     infoObj.Sr = Convert.ToInt32(info[0].ToString());  
  122.                     infoObj.OrderTrackNumber = info[1].ToString();  
  123.                     infoObj.Quantity = Convert.ToInt32(info[2].ToString());  
  124.                     infoObj.ProductName = info[3].ToString();  
  125.                     infoObj.SpecialOffer = info[4].ToString();  
  126.                     infoObj.UnitPrice = Convert.ToDouble(info[5].ToString());  
  127.                     infoObj.UnitPriceDiscount = Convert.ToDouble(info[6].ToString());  
  128.   
  129.                     // Adding.  
  130.                     lst.Add(infoObj);  
  131.                 }  
  132.   
  133.                 // Closing.  
  134.                 sr.Dispose();  
  135.                 sr.Close();  
  136.             }  
  137.             catch (Exception ex)  
  138.             {  
  139.                 // info.  
  140.                 Console.Write(ex);  
  141.             }  
  142.   
  143.             // info.  
  144.             return lst;  
  145.         }  
  146.  
  147.         #endregion  
  148.  
  149.         #endregion  
  150.     }  

In the above code, I have created a simple Page_Load() action method along with a helper method LoadData() for data loading from text file and finally GetData() WebMethod method which will be called by Google charts API Ajax method in order to map data on the chart. The GetData() WebMethod method will return the top 10 rows only, which are sorted by product quantity and grouped by product name.

Step 7

Create a new "Scripts\custom-graph.js" script file and replace the following code in it:

  1. // Load the Visualization API and the piechart package.  
  2. google.load('visualization''1.0', { 'packages': ['corechart'] });  
  3.   
  4. // Set a callback to run when the Google Visualization API is loaded.  
  5. $(document).ready(function ()  
  6. {  
  7.     $.ajax(  
  8.     {  
  9.         type: 'GET',  
  10.         dataType: 'JSON',  
  11.         contentType: 'application/json',  
  12.         url: 'Default.aspx/GetData',  
  13.         success:  
  14.             function (response)  
  15.             {  
  16.                 // Set chart options  
  17.                 var options =  
  18.                     {  
  19.                         width: 1100,  
  20.                         height: 900,  
  21.                         sliceVisibilityThreshold: 0,  
  22.                         legend: { position: "top", alignment: "end" },  
  23.                         chartArea: { left: 370, top: 50, height: "90%" },  
  24.                         hAxis:  
  25.                             {  
  26.                                 slantedText: true,  
  27.                                 slantedTextAngle: 18  
  28.                             },  
  29.                         bar: { groupWidth: "50%" },  
  30.                     };  
  31.   
  32.                 // Draw.  
  33.                 drawGraph(response.d, options, 'graphId');  
  34.             }  
  35.     });  
  36. });  
  37.   
  38. // Callback that creates and populates a data table,  
  39. // instantiates the pie chart, passes in the data and  
  40. // draws it.  
  41. function drawGraph(dataValues, options, elementId)  
  42. {  
  43.     // Initialization.  
  44.     var data = new google.visualization.DataTable();  
  45.   
  46.     // Setting.  
  47.     data.addColumn('string''Product Name');  
  48.     data.addColumn('number''Unit Price');  
  49.     data.addColumn('number''Quantity');  
  50.   
  51.     // Processing.  
  52.     for (var i = 0; i < dataValues.length; i++)  
  53.     {  
  54.         // Setting.  
  55.         data.addRow([dataValues[i].ProductName, dataValues[i].UnitPrice, dataValues[i].Quantity]);  
  56.     }  
  57.   
  58.     // Setting label.  
  59.     var view = new google.visualization.DataView(data);  
  60.     view.setColumns([0, 1,  
  61.         {  
  62.             calc: "stringify",  
  63.             sourceColumn: 1,  
  64.             type: "string",  
  65.             role: "annotation"  
  66.         },  
  67.         2,  
  68.         {  
  69.             calc: "stringify",  
  70.             sourceColumn: 2,  
  71.             type: "string",  
  72.             role: "annotation"  
  73.         }  
  74.     ]);  
  75.   
  76.     // Instantiate and draw our chart, passing in some options.  
  77.     var chart = new google.visualization.BarChart(document.getElementById(elementId));  
  78.   
  79.     // Draw chart.  
  80.     chart.draw(view, options);  

Let's break down the code chunk by chunk. First I have loaded the Google charts API charts visualization package:

  1. // Load the Visualization API and the piechart package.  
  2. google.load('visualization''1.0', { 'packages': ['corechart'] }); 

Then I call the GetData() server side method via Ajax call and after successfully receiving the data, I simply set default chart options then passed those options to a user defined javaScript method "drawGraph(...)" 

  1. // Set a callback to run when the Google Visualization API is loaded.  
  2. $(document).ready(function ()  
  3. {  
  4.     $.ajax(  
  5.     {  
  6.         type: 'GET',  
  7.         dataType: 'JSON',  
  8.         contentType: 'application/json',  
  9.         url: 'Default.aspx/GetData',  
  10.         success:  
  11.             function (response)  
  12.             {  
  13.                 // Set chart options  
  14.                 var options =  
  15.                     {  
  16.                         width: 1100,  
  17.                         height: 900,  
  18.                         sliceVisibilityThreshold: 0,  
  19.                         legend: { position: "top", alignment: "end" },  
  20.                         chartArea: { left: 370, top: 50, height: "90%" },  
  21.                         hAxis:  
  22.                             {  
  23.                                 slantedText: true,  
  24.                                 slantedTextAngle: 18  
  25.                             },  
  26.                         bar: { groupWidth: "50%" },  
  27.                     };  
  28.   
  29.                 // Draw.  
  30.                 drawGraph(response.d, options, 'graphId');  
  31.             }  
  32.     });  
  33. }); 

Now, in the below drawGraph(...) method code, I added three new columns per row, the 0 column will be the name of the products which will be shown on the chart axis, 1st column will be the unit price of the product which will be shown on the graph and 2nd column will be the quantity of the product which will also be shown on the graph for each product. After adding the column metadata for the chart, I will convert the received data from the server into DataTables data type accepted by the chart. Then I will set the annotation option for the 1st & 2nd column which will display the corresponding values on the chart columns per each product. Finally, I will draw the BarChart by calling Google charts API method:

  1. // Callback that creates and populates a data table,  
  2. // instantiates the pie chart, passes in the data and  
  3. // draws it.  
  4. function drawGraph(dataValues, options, elementId) {  
  5.     // Initialization.  
  6.     var data = new google.visualization.DataTable();  
  7.   
  8.     // Setting.  
  9.     data.addColumn('string''Product Name');  
  10.     data.addColumn('number''Unit Price');  
  11.     data.addColumn('number''Quantity');  
  12.   
  13.     // Processing.  
  14.     for (var i = 0; i < dataValues.length; i++)  
  15.     {  
  16.         // Setting.  
  17.         data.addRow([dataValues[i].ProductName, dataValues[i].UnitPrice, dataValues[i].Quantity]);  
  18.     }  
  19.   
  20.     // Setting label.  
  21.     var view = new google.visualization.DataView(data);  
  22.     view.setColumns([0, 1,  
  23.         {  
  24.             calc: "stringify",  
  25.             sourceColumn: 1,  
  26.             type: "string",  
  27.             role: "annotation"  
  28.         },  
  29.         2,  
  30.         {  
  31.             calc: "stringify",  
  32.             sourceColumn: 2,  
  33.             type: "string",  
  34.             role: "annotation"  
  35.         }  
  36.     ]);  
  37.   
  38.     // Instantiate and draw our chart, passing in some options.  
  39.     var chart = new google.visualization.BarChart(document.getElementById(elementId));  
  40.   
  41.     // Draw chart.  
  42.     chart.draw(view, options);  

Step 8

Open "Default.aspx" file and replace the following code in it:

  1. <%@ Page Title="ASP.NET Webform - Google Graph Integration" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GoogleGraphsWebform._Default" %>  
  2.   
  3. <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">  
  4.   
  5.     <div class="row">  
  6.         <div class="panel-heading">  
  7.             <div class="col-md-8">  
  8.                 <h3>  
  9.                     <i class="fa fa-pie-chart"></i>  
  10.                     <span>ASP.NET Webform - Google Graph Integration </span>  
  11.                 </h3>  
  12.             </div>  
  13.         </div>  
  14.     </div>  
  15.   
  16.     <div class="row">  
  17.         <section class="col-md-12 col-md-push-0">  
  18.             <section>  
  19.                 <div class="well bs-component">  
  20.                     <br />  
  21.   
  22.                     <div class="row">  
  23.                         <div class="col-xs-12">  
  24.                             <!-- CHART -->  
  25.                             <div class="box box-primary">  
  26.                                 <div class="box-header with-border">  
  27.                                     <h3 class="box-title custom-heading">Product wise Graph</h3>  
  28.                                 </div>  
  29.                                 <div class="box-body">  
  30.                                     <div class="chart">  
  31.                                         <div id="graphId" style="width: 1100px; height: 900px; margin:auto;"></div>  
  32.                                     </div>  
  33.                                 </div><!-- /.box-body -->  
  34.                             </div><!-- /.box -->  
  35.                         </div>  
  36.                     </div>  
  37.                 </div>  
  38.             </section>  
  39.         </section>  
  40.     </div>  
  41. </asp:Content> 

In the above code, I have simply created the view code for the page which will display the chart. I have divided the page into two parts for better manageability. Notice that, I have added width & height values for the graph div:

  1. <div id="graphId" style="width: 1100px; height: 900px; margin:auto;"></div> 

The above setting is important in order to properly set the chart area on the HTML page. The same width & height is set with chart options as well in the JavaScript file:

  1. var options =  
  2.      {  
  3.          width: 1100,  
  4.          height: 900,  
  5.          sliceVisibilityThreshold: 0,  
  6.          legend: { position: "top", alignment: "end" },  
  7.          chartArea: { left: 370, top: 50, height: "90%" },  
  8.          hAxis:  
  9.              {  
  10.                  slantedText: true,  
  11.                  slantedTextAngle: 18  
  12.              },  
  13.          bar: { groupWidth: "50%" },  
  14.      }; 

Play around with the rest of the properties to understand the chart options better.

Step 9

Execute the project and you will be able to see the following:


Conclusion

In this article, you learned to integrate Google charts API into asp.net webform projects. You also learned about basic options of the chart. You also learned about the data passing to front view through ajax call using WebMethod attribute of asp.net webform and you learned to represent your data as a graphical entity in order to perform analysis for better decision making.


Similar Articles