Understanding data is never a simple process; it involves a lot of pre and post-processing in order to make sense out of the data that has been collected. After understanding the data and extracting meaningful information, the next step is the presentation of the data, i.e., how to present the data to make analytical sense out of it which ultimately leads to better decision making. Graphs are one form of representing the data which helps in making meaningful reports for analytical purposes that eventually helps stakeholders to make a better decision.
Today, I shall be demonstrating the integration of Google Charts API with ASP.NET MVC5. Google Charts API is simple to use and provides a variety of options for customization of graphical chart reports for better analytics.
Following are some prerequisites before you proceed further in this tutorial.
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.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
-
-
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
-
- @* Custom *@
- @Styles.Render("~/Content/css/custom-style")
- </head>
- <body>
- <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">
- @RenderBody()
- <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>
-
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
-
-
- <script type="text/javascript" src="https://www.google.com/jsapi"></script>
- @Scripts.Render("~/bundles/Script-custom-graphs")
-
- @RenderSection("scripts", required: false)
- </body>
- </html>
In the above code, I have simply created the basic layout structure of this web project and I have also added reference to the
Google Charts API.
Step 3
Create a new "Models\HomeViewModels.cs" file and replace the code with the following.
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
-
- namespace Graphs.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, we have simply created our View Model which will map the data from text file into main memory as object.
Step 4
Now create "Controllers\HomeController.cs" file and replace the code with the following code.
In the above code, I have created a simple index() action method 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 10 rows only which are sorted by product quantity and group by product name.
Step 5
Create a new "Scripts\script-custom-graphs.js" script file and replace the code with the following one.
-
- google.load('visualization', '1.0', { 'packages': ['corechart'] });
-
-
- $(document).ready(function ()
- {
- $.ajax(
- {
- type: 'POST',
- dataType: 'JSON',
- url: '/Home/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, 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 the default chart options then passed those options to a user-defined JavaScript method "drawGraph(...)".
-
- $(document).ready(function ()
- {
- $.ajax(
- {
- type: 'POST',
- dataType: 'JSON',
- url: '/Home/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, options, 'graphId');
- }
- });
- });
Now, in the below drwGraph(...) method code, I add three new columns per row. The 0th 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 wil be shown on the graph, and the 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 first and second column which will display the correspondent values on the chart columns per each product. Finally, I will draw the BarChart by calling Google charts API method i.e.
-
-
-
- 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);
- }
6
Create "Views\Home\_ViewGraphPartial.cshtml" & "Views\Home\Index.cshtml" files and replace the code with the following.
Views\Home\_ViewGraphPartial.cshtml
- <section>
- <div class="well bs-component">
- <div class="row">
- <div class="col-xs-12">
-
- <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>
- </div>
- </div>
- </div>
- </div>
- </section>
View\Home\Index.cshtml
- @{
- ViewBag.Title = "ASP.NET MVC5 - Google Graph Integration";
- }
-
- <div class="row">
- <div class="panel-heading">
- <div class="col-md-8 custom-heading3">
- <h3>
- <i class="fa fa-pie-chart"></i>
- <span>ASP.NET MVC5 - Google Graph Integration</span>
- </h3>
- </div>
- </div>
- </div>
-
- <div class="row">
- <section class="col-md-12 col-md-push-0">
- @Html.Partial("_ViewGraphPartial")
- </section>
- </div>
In the above code, I have simply create the view code for the page which will display the chart. I have divided the page into two parts for better manageability. Notice that, in the "Views\Home\_ViewGraphPartial.cshtml" file, I have added width & height values for the graph div i.e.
- <div id="graphId" style="width: 1100px; height: 900px; margin:auto;"></div>
Above setting is important in order to properly set the chart area on the HTML page. 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 rest of the properties to understand chart options better.
Step 7
Execute the project and you will be able to see the following screen.
Conclusion
In this article, we learned how to integrate Google Charts API into ASP.NET MVC 5 project. We also learned about passing the data to front view through AJAX call and saw how to represent our data as a graphical entity in order to perform analysis for better decision making.