ASP.NET MVC 5 - Clickable Google Charts

This article is about Google Charts interactivity through click event on the chart.

Charts are an important aspect of reports as they make it simpler to understand a certain problem. Making charts clickable adds more reinforcement into the understanding of the problem.

Today, I shall be demonstrating clickable charts using Google Charts API in ASP.NET MVC5. 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 ASP.NET MVC5.
  3. Knowledge of HTML.
  4. Knowledge of JavaScript.
  5. Knowledge of AJAX.
  6. Knowledge of CSS.
  7. Knowledge of Bootstrap.
  8. Knowledge of C# programming.
  9. Knowledge of C# LINQ.
  10. 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 extracted from Adventure Works Sample Database.

Let's begin now.

Step 1

Create a new MVC5 web application project and name it "Graphs".

Step 2

Open "Views\Shared\_Layout.cshtml" file and replace the following code in it.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10.     <!-- Font Awesome -->  
  11.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
  12.   
  13.     @* Custom *@  
  14.     @Styles.Render("~/Content/css/custom-style")  
  15. </head>  
  16. <body>  
  17.     <div class="navbar navbar-inverse navbar-fixed-top">  
  18.         <div class="container">  
  19.             <div class="navbar-header">  
  20.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  21.                     <span class="icon-bar"></span>  
  22.                     <span class="icon-bar"></span>  
  23.                     <span class="icon-bar"></span>  
  24.                 </button>  
  25.             </div>  
  26.         </div>  
  27.     </div>  
  28.     <div class="container body-content">  
  29.         @RenderBody()  
  30.         <hr />  
  31.         <footer>  
  32.             <center>  
  33.                 <p><strong>Copyright © @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
  34.             </center>  
  35.         </footer>  
  36.     </div>  
  37.   
  38.     @Scripts.Render("~/bundles/jquery")  
  39.     @Scripts.Render("~/bundles/bootstrap")  
  40.   
  41.     <!-- Graphs -->  
  42.     <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
  43.     @Scripts.Render("~/bundles/Script-custom-graphs")  
  44.   
  45.     @RenderSection("scripts", required: false)  
  46. </body>  
  47. </html> 

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

Step 3

Create a new "Models\HomeViewModels.cs" file and replace with the following code in it.

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

In the above code, we have simply created our View Model which will map the data from text file into main memory as object. Also, notice that we have added "Link" property, which we will use as our clickable destination.

Step 4

Now, create "Controllers\HomeController.cs" file and replace the following code in it.

  1. using Graphs.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.Mvc;  
  9.   
  10. namespace Graphs.Controllers  
  11. {  
  12.     public class HomeController : Controller  
  13.     {  
  14.         #region Index method  
  15.   
  16.         /// <summary>  
  17.         /// GET: Home/Index method.  
  18.         /// </summary>  
  19.         /// <returns>Returns - index view page</returns>   
  20.         public ActionResult Index()  
  21.         {  
  22.             // Info.  
  23.             return this.View();  
  24.         }  
  25.  
  26.         #endregion  
  27.  
  28.         #region Test Page method  
  29.   
  30.         /// <summary>  
  31.         /// GET: Home/TestPage method.  
  32.         /// </summary>  
  33.         /// <returns>Returns - test page view page</returns>   
  34.         public ActionResult TestPage()  
  35.         {  
  36.             // Info.  
  37.             return this.View();  
  38.         }  
  39.  
  40.         #endregion  
  41.  
  42.         #region Get data method.  
  43.   
  44.         /// <summary>  
  45.         /// GET: /Home/GetData  
  46.         /// </summary>  
  47.         /// <returns>Return data</returns>  
  48.         public ActionResult GetData()  
  49.         {  
  50.             // Initialization.  
  51.             JsonResult result = new JsonResult();  
  52.   
  53.             try  
  54.             {  
  55.                 // Loading.  
  56.                 List<SalesOrderDetail> data = this.LoadData();  
  57.   
  58.                 // Setting.  
  59.                 var graphData = data.GroupBy(p => new  
  60.                                     {  
  61.                                         p.ProductName,  
  62.                                         p.Link,  
  63.                                         p.UnitPrice  
  64.                                     })  
  65.                                     .Select(g => new  
  66.                                     {  
  67.                                         g.Key.ProductName,  
  68.                                         g.Key.Link,  
  69.                                         g.Key.UnitPrice  
  70.                                     }).OrderByDescending(q => q.UnitPrice).ToList();  
  71.   
  72.                 // Top 10  
  73.                 graphData = graphData.Take(2).Select(p => p).ToList();  
  74.   
  75.                 // Loading drop down lists.  
  76.                 result = this.Json(graphData, JsonRequestBehavior.AllowGet);  
  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 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.                     infoObj.Link = this.Url.Action("TestPage""Home");  
  129.   
  130.                     // Adding.  
  131.                     lst.Add(infoObj);  
  132.                 }  
  133.   
  134.                 // Closing.  
  135.                 sr.Dispose();  
  136.                 sr.Close();  
  137.             }  
  138.             catch (Exception ex)  
  139.             {  
  140.                 // info.  
  141.                 Console.Write(ex);  
  142.             }  
  143.   
  144.             // info.  
  145.             return lst;  
  146.         }  
  147.  
  148.         #endregion  
  149.  
  150.         #endregion  
  151.     }  

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

Step 5

Create a new "Scripts\script-custom-graphs.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: 'POST',  
  10.         dataType: 'JSON',  
  11.         url: '/Home/GetData',  
  12.         success:  
  13.             function (response)  
  14.             {  
  15.                 // Set chart options  
  16.                 var options =  
  17.                     {  
  18.                         width: 1100,  
  19.                         height: 900,  
  20.                         sliceVisibilityThreshold: 0,  
  21.                         legend: { position: "top", alignment: "end" },  
  22.                         chartArea: { left: 370, top: 50, height: "90%" },  
  23.   
  24.                         bar: { groupWidth: "50%" },  
  25.                     };  
  26.   
  27.                 // Draw.  
  28.                 drawGraph(response, options, 'graphId');  
  29.             }  
  30.     });  
  31. });  
  32.   
  33. // Callback that creates and populates a data table,  
  34. // instantiates the pie chart, passes in the data and  
  35. // draws it.  
  36. function drawGraph(dataValues, options, elementId) {  
  37.     // Initialization.  
  38.     var data = new google.visualization.DataTable();  
  39.   
  40.     // Setting.  
  41.     data.addColumn('string''Product Name');  
  42.     data.addColumn('number''Unit Price');  
  43.     data.addColumn('string''Link');  
  44.   
  45.     // Processing.  
  46.     for (var i = 0; i < dataValues.length; i++)  
  47.     {  
  48.         // Setting.  
  49.         data.addRow([dataValues[i].ProductName, dataValues[i].UnitPrice, dataValues[i].Link]);  
  50.     }  
  51.   
  52.     // Setting label.  
  53.     var view = new google.visualization.DataView(data);  
  54.     view.setColumns([0, 1,  
  55.         {  
  56.             calc: "stringify",  
  57.             sourceColumn: 1,  
  58.             type: "string",  
  59.             role: "annotation"  
  60.         }  
  61.     ]);  
  62.   
  63.     // Instantiate and draw our chart, passing in some options.  
  64.     var chart = new google.visualization.ColumnChart(document.getElementById(elementId));  
  65.   
  66.     // Draw chart.  
  67.     chart.draw(view, options);  
  68.   
  69.     // Link interaction.  
  70.     var selectHandler = function (e)  
  71.     {  
  72.         // Verification.  
  73.         if (chart.getSelection() != null &&  
  74.              chart.getSelection()[0] != null &&  
  75.              chart.getSelection()[0]['row'] != null &&  
  76.              chart.getSelection().length > 0)  
  77.         {  
  78.             if (chart.getSelection()[0]['column'] == 1)  
  79.             {  
  80.                 // Setting.  
  81.                 var link = data.getValue(chart.getSelection()[0]['row'], 2)  
  82.                 window.open(link, '_blank');  
  83.             }  
  84.         }  
  85.     }  
  86.   
  87.     // Add our selection handler.  
  88.     google.visualization.events.addListener(chart, 'select', selectHandler);  

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 the default chart options then pass those options to a user-define 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: 'POST',  
  7.         dataType: 'JSON',  
  8.         url: '/Home/GetData',  
  9.         success:  
  10.             function (response)  
  11.             {  
  12.                 // Set chart options  
  13.                 var options =  
  14.                     {  
  15.                         width: 1100,  
  16.                         height: 900,  
  17.                         sliceVisibilityThreshold: 0,  
  18.                         legend: { position: "top", alignment: "end" },  
  19.                         chartArea: { left: 370, top: 50, height: "90%" },  
  20.                         hAxis:  
  21.                             {  
  22.                                 slantedText: true,  
  23.                                 slantedTextAngle: 18  
  24.                             },  
  25.                         bar: { groupWidth: "50%" },  
  26.                     };  
  27.   
  28.                 // Draw.  
  29.                 drawGraph(response, options, 'graphId');  
  30.             }  
  31.     });  
  32. }); 

Now, in the below drawGraph(...) method code, I add three new columns per row, the zero column will be the name of the products which will be shown on the chart axis, the first column will be the unit price of the product which will 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 first chart column which will display the correspondent values on the chart columns per each product. Then, I will draw the ColumnChart by calling Google charts API method. Next, I add the selection handler which will map target link to the target chart display column. Finally, I add the listener event which will call our selection handler method and open the link in a new window as we have coded in the selection handler; i.e.:

  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('string''Link');  
  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].Link]);  
  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.     ]);  
  30.   
  31.     // Instantiate and draw our chart, passing in some options.  
  32.     var chart = new google.visualization.ColumnChart(document.getElementById(elementId));  
  33.   
  34.     // Draw chart.  
  35.     chart.draw(view, options);  
  36.   
  37.     // Link interaction.  
  38.     var selectHandler = function (e)  
  39.     {  
  40.         // Verification.  
  41.         if (chart.getSelection() != null &&  
  42.              chart.getSelection()[0] != null &&  
  43.              chart.getSelection()[0]['row'] != null &&  
  44.              chart.getSelection().length > 0)  
  45.         {  
  46.             if (chart.getSelection()[0]['column'] == 1)  
  47.             {  
  48.                 // Setting.  
  49.                 var link = data.getValue(chart.getSelection()[0]['row'], 2)  
  50.                 window.open(link, '_blank');  
  51.             }  
  52.         }  
  53.     }  
  54.   
  55.     // Add our selection handler.  
  56.     google.visualization.events.addListener(chart, 'select', selectHandler);  

Step 6

Create "Views\Home\_ViewGraphPartial.cshtml" & "Views\Home\Index.cshtml" files and replace following code in it.

Views\Home\_ViewGraphPartial.cshtml

  1. <section>  
  2.     <div class="well bs-component">  
  3.         <div class="row">  
  4.             <div class="col-xs-12">  
  5.                 <!-- CHART -->  
  6.                 <div class="box box-primary">  
  7.                     <div class="box-header with-border">  
  8.                         <h3 class="box-title custom-heading">Product wise Graph</h3>  
  9.                     </div>  
  10.                     <div class="box-body">  
  11.                         <div class="chart">  
  12.                             <div id="graphId" style="width: 1100px; height: 900px; margin:auto;"></div>  
  13.                         </div>  
  14.                     </div><!-- /.box-body -->  
  15.                 </div><!-- /.box -->  
  16.             </div>  
  17.         </div>  
  18.     </div>  
  19. </section> 

View\Home\Index.cshtml

  1. @{  
  2.     ViewBag.Title = "ASP.NET MVC5 - Clickable Google Charts";  
  3. }  
  4.   
  5. <div class="row">  
  6.     <div class="panel-heading">  
  7.         <div class="col-md-8  custom-heading3">  
  8.             <h3>  
  9.                 <i class="fa fa-pie-chart"></i>  
  10.                 <span>ASP.NET MVC5 - Clickable Google Charts</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.         @Html.Partial("_ViewGraphPartial")  
  19.     </section>  
  20. </div> 

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.

Step 7

Now, create new "Views\Home\TestPage.cshtml" file and replace following code in it.

  1. @{  
  2.     ViewBag.Title = "ASP.NET MVC5 - Clickable Google Charts";  
  3. }  
  4.   
  5. <div class="row">  
  6.     <div class="panel-heading">  
  7.         <div class="col-md-8  custom-heading3">  
  8.             <h3>  
  9.                 <i class="fa fa-pie-chart"></i>  
  10.                 <span>ASP.NET MVC5 - Clickable Google Charts</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.         <div class="well bs-component">  
  19.             <div class="row">  
  20.                 <div class="col-xs-12">  
  21.                     <h1>Hello! I am Clickable Test Page</h1>  
  22.                 </div>  
  23.             </div>  
  24.         </div>  
  25.     </section>  
  26. </div> 

In the above code, I have simply added a new page structure for the chart click event target.

Step 8

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




Conclusion

 

In this article, we have learned how to make charts clickable using Google Charts. We also learned to integrate Google charts API into asp.net mvc5 project.