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:
- Knowledge of Google charts API.
- Knowledge of classic ASP.NET webform.
- Knowledge of WebMethod attribute.
- Knowledge of HTML.
- Knowledge of JavaScript.
- Knowledge of AJAX.
- Knowledge of CSS.
- Knowledge of Bootstrap.
- Knowledge of C# programming.
- Knowledge of C# LINQ.
- 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:
- using System;
- using System.Collections.Generic;
- using System.Web;
- using System.Web.Routing;
- using Microsoft.AspNet.FriendlyUrls;
-
- namespace GoogleGraphsWebform
- {
- public static class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- var settings = new FriendlyUrlSettings();
- settings.AutoRedirectMode = RedirectMode.Off;
- routes.EnableFriendlyUrls(settings);
- }
- }
- }
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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Optimization;
- using System.Web.UI;
-
- namespace GoogleGraphsWebform
- {
- public class BundleConfig
- {
-
- public static void RegisterBundles(BundleCollection bundles)
- {
- bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(
- "~/Scripts/WebForms/WebForms.js",
- "~/Scripts/WebForms/WebUIValidation.js",
- "~/Scripts/WebForms/MenuStandards.js",
- "~/Scripts/WebForms/Focus.js",
- "~/Scripts/WebForms/GridView.js",
- "~/Scripts/WebForms/DetailsView.js",
- "~/Scripts/WebForms/TreeView.js",
- "~/Scripts/WebForms/WebParts.js"));
-
-
- bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include(
- "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js",
- "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js",
- "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js",
- "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js"));
-
-
-
- bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
- "~/Scripts/modernizr-*"));
-
- bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
- "~/Scripts/jquery-{version}.js"));
-
- bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
- "~/Scripts/jquery.validate*"));
-
- bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
- "~/Scripts/bootstrap.js",
- "~/Scripts/respond.js"));
-
- ScriptManager.ScriptResourceMapping.AddDefinition(
- "respond",
- new ScriptResourceDefinition
- {
- Path = "~/Scripts/respond.min.js",
- DebugPath = "~/Scripts/respond.js",
- });
- }
- }
- }
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:
- <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="GoogleGraphsWebform.SiteMaster" %>
-
- <!DOCTYPE html>
-
- <html lang="en">
- <head runat="server">
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title><%: Page.Title %></title>
-
- <asp:PlaceHolder runat="server">
- <%: Scripts.Render("~/bundles/modernizr") %>
- <%: Scripts.Render("~/bundles/jquery") %>
- </asp:PlaceHolder>
- <webopt:bundlereference runat="server" path="~/Content/css" />
- <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
-
-
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
-
-
- <script type="text/javascript" src="https://www.google.com/jsapi"></script>
- <script src="Scripts/custom-graph.js" type="text/javascript"></script>
-
- </head>
- <body>
- <form runat="server">
- <asp:ScriptManager runat="server">
- <Scripts>
- <%--To learn more about bundling scripts in ScriptManager see http://go.microsoft.com/fwlink/?LinkID=301884 --%>
- <%--Framework Scripts--%>
- <asp:ScriptReference Name="MsAjaxBundle" />
- <%-- <asp:ScriptReference Name="jquery" />--%>
- <asp:ScriptReference Name="bootstrap" />
- <asp:ScriptReference Name="respond" />
- <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
- <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
- <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
- <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
- <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
- <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
- <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
- <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
- <asp:ScriptReference Name="WebFormsBundle" />
- <%--Site Scripts--%>
- </Scripts>
- </asp:ScriptManager>
-
- <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>
- </div>
- </div>
- </div>
-
- <div class="container body-content">
- <asp:ContentPlaceHolder ID="MainContent" runat="server">
- </asp:ContentPlaceHolder>
- <hr />
- <footer>
- <center>
- <p><strong>Copyright © <%: DateTime.Now.Year %> - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
- </center>
- </footer>
- </div>
- </form>
- </body>
- </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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace GoogleGraphsWebform.Models
- {
- public class SalesOrderDetail
- {
- public int Sr { get; set; }
- public string OrderTrackNumber { get; set; }
- public int Quantity { get; set; }
- public string ProductName { get; set; }
- public string SpecialOffer { get; set; }
- public double UnitPrice { get; set; }
- public double UnitPriceDiscount { get; set; }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace GoogleGraphsWebform.Models
- {
- public class GraphData
- {
- public int Quantity { get; set; }
- public string ProductName { get; set; }
- public double UnitPrice { get; set; }
- }
- }
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:
- using GoogleGraphsWebform.Models;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Web;
- using System.Web.Script.Services;
- using System.Web.Services;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace GoogleGraphsWebform
- {
- public partial class _Default : Page
- {
- #region Page Load event
-
- protected void Page_Load(object sender, EventArgs e)
- {
- try
- {
-
- Console.Write("test");
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
- }
-
- #endregion
-
- #region Get data method.
-
-
-
-
-
- [WebMethod]
- [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
- public static List<GraphData> GetData()
- {
-
- List<GraphData> result = new List<GraphData>();
-
- try
- {
-
- List<SalesOrderDetail> data = _Default.LoadData();
-
-
- var graphData = data.GroupBy(p => new
- {
- p.ProductName,
- p.Quantity,
- p.UnitPrice
- })
- .Select(g => new
- {
- g.Key.ProductName,
- g.Key.Quantity,
- g.Key.UnitPrice
- }).OrderByDescending(q => q.Quantity).ToList();
-
-
- graphData = graphData.Take(10).Select(p => p).ToList();
-
-
- result = graphData.Select(p => new GraphData
- {
- ProductName = p.ProductName,
- Quantity = p.Quantity,
- UnitPrice = p.UnitPrice
- }).ToList();
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
-
- return result;
- }
-
- #endregion
-
- #region Helpers
-
- #region Load Data
-
-
-
-
-
- private static List<SalesOrderDetail> LoadData()
- {
-
- List<SalesOrderDetail> lst = new List<SalesOrderDetail>();
-
- try
- {
-
- string line = string.Empty;
- string srcFilePath = "Content/files/SalesOrderDetail.txt";
- var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
- var fullPath = Path.Combine(rootPath, srcFilePath);
- string filePath = new Uri(fullPath).LocalPath;
- StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
-
-
- while ((line = sr.ReadLine()) != null)
- {
-
- SalesOrderDetail infoObj = new SalesOrderDetail();
- string[] info = line.Split(',');
-
-
- infoObj.Sr = Convert.ToInt32(info[0].ToString());
- infoObj.OrderTrackNumber = info[1].ToString();
- infoObj.Quantity = Convert.ToInt32(info[2].ToString());
- infoObj.ProductName = info[3].ToString();
- infoObj.SpecialOffer = info[4].ToString();
- infoObj.UnitPrice = Convert.ToDouble(info[5].ToString());
- infoObj.UnitPriceDiscount = Convert.ToDouble(info[6].ToString());
-
-
- lst.Add(infoObj);
- }
-
-
- sr.Dispose();
- sr.Close();
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
-
- return lst;
- }
-
- #endregion
-
- #endregion
- }
- }
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:
-
- google.load('visualization', '1.0', { 'packages': ['corechart'] });
-
-
- $(document).ready(function ()
- {
- $.ajax(
- {
- type: 'GET',
- dataType: 'JSON',
- contentType: 'application/json',
- url: 'Default.aspx/GetData',
- success:
- function (response)
- {
-
- var options =
- {
- width: 1100,
- height: 900,
- sliceVisibilityThreshold: 0,
- legend: { position: "top", alignment: "end" },
- chartArea: { left: 370, top: 50, height: "90%" },
- hAxis:
- {
- slantedText: true,
- slantedTextAngle: 18
- },
- bar: { groupWidth: "50%" },
- };
-
-
- drawGraph(response.d, options, 'graphId');
- }
- });
- });
-
-
-
-
- function drawGraph(dataValues, options, elementId)
- {
-
- var data = new google.visualization.DataTable();
-
-
- data.addColumn('string', 'Product Name');
- data.addColumn('number', 'Unit Price');
- data.addColumn('number', 'Quantity');
-
-
- for (var i = 0; i < dataValues.length; i++)
- {
-
- data.addRow([dataValues[i].ProductName, dataValues[i].UnitPrice, dataValues[i].Quantity]);
- }
-
-
- var view = new google.visualization.DataView(data);
- view.setColumns([0, 1,
- {
- calc: "stringify",
- sourceColumn: 1,
- type: "string",
- role: "annotation"
- },
- 2,
- {
- calc: "stringify",
- sourceColumn: 2,
- type: "string",
- role: "annotation"
- }
- ]);
-
-
- var chart = new google.visualization.BarChart(document.getElementById(elementId));
-
-
- chart.draw(view, options);
- }
Let's break down the code chunk by chunk. First I have loaded the Google charts API charts visualization package:
-
- 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(...)"
-
- $(document).ready(function ()
- {
- $.ajax(
- {
- type: 'GET',
- dataType: 'JSON',
- contentType: 'application/json',
- url: 'Default.aspx/GetData',
- success:
- function (response)
- {
-
- var options =
- {
- width: 1100,
- height: 900,
- sliceVisibilityThreshold: 0,
- legend: { position: "top", alignment: "end" },
- chartArea: { left: 370, top: 50, height: "90%" },
- hAxis:
- {
- slantedText: true,
- slantedTextAngle: 18
- },
- bar: { groupWidth: "50%" },
- };
-
-
- drawGraph(response.d, options, 'graphId');
- }
- });
- });
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:
-
-
-
- function drawGraph(dataValues, options, elementId) {
-
- var data = new google.visualization.DataTable();
-
-
- data.addColumn('string', 'Product Name');
- data.addColumn('number', 'Unit Price');
- data.addColumn('number', 'Quantity');
-
-
- for (var i = 0; i < dataValues.length; i++)
- {
-
- data.addRow([dataValues[i].ProductName, dataValues[i].UnitPrice, dataValues[i].Quantity]);
- }
-
-
- var view = new google.visualization.DataView(data);
- view.setColumns([0, 1,
- {
- calc: "stringify",
- sourceColumn: 1,
- type: "string",
- role: "annotation"
- },
- 2,
- {
- calc: "stringify",
- sourceColumn: 2,
- type: "string",
- role: "annotation"
- }
- ]);
-
-
- var chart = new google.visualization.BarChart(document.getElementById(elementId));
-
-
- chart.draw(view, options);
- }
Step 8
Open "Default.aspx" file and replace the following code in it:
- <%@ Page Title="ASP.NET Webform - Google Graph Integration" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GoogleGraphsWebform._Default" %>
-
- <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
-
- <div class="row">
- <div class="panel-heading">
- <div class="col-md-8">
- <h3>
- <i class="fa fa-pie-chart"></i>
- <span>ASP.NET Webform - Google Graph Integration </span>
- </h3>
- </div>
- </div>
- </div>
-
- <div class="row">
- <section class="col-md-12 col-md-push-0">
- <section>
- <div class="well bs-component">
- <br />
-
- <div class="row">
- <div class="col-xs-12">
- <!-- CHART -->
- <div class="box box-primary">
- <div class="box-header with-border">
- <h3 class="box-title custom-heading">Product wise Graph</h3>
- </div>
- <div class="box-body">
- <div class="chart">
- <div id="graphId" style="width: 1100px; height: 900px; margin:auto;"></div>
- </div>
- </div><!-- /.box-body -->
- </div><!-- /.box -->
- </div>
- </div>
- </div>
- </section>
- </section>
- </div>
- </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:
- <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:
- var options =
- {
- width: 1100,
- height: 900,
- sliceVisibilityThreshold: 0,
- legend: { position: "top", alignment: "end" },
- chartArea: { left: 370, top: 50, height: "90%" },
- hAxis:
- {
- slantedText: true,
- slantedTextAngle: 18
- },
- bar: { groupWidth: "50%" },
- };
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.