Make Your MVC Web Applications Beautiful with Google Charts
October 6, 2016

I recently was asked to develop a dashboard application for tracking the data flow metrics for a large financial firm. Having had no experience developing a ‘dashboard’ application, I began to do some research into how I could do this efficiently and with a minimum amount of effort designing the user interface.
Like most application developers, I am somewhat aesthetically challenged when it comes to web page design. When I began to research what tools were available to me as far as charts and graphs that could be quickly and easily integrated into a web application, I came across the Google Charts application interface. I know this technology has been around for a while, but it is still relevant for creating nicely formatted charts and graphs for web pages such as the ones that I needed to design for my ‘dashboard’ application.
This blog will show you how to quickly and easily integrate a simple bar graph into your MVC application using C# for the server side processing and Java Script for the presentation layer.
Step 1 – Create a MVC Web Application in Visual Studio.
Open Visual Studio and create a new MVC web application. I named mine ‘MVCGraphApp1’. Your solution explorer view should look like the following when you are done:
Right click on the ‘Controllers’ folder and select ‘Add’ and then select ‘Controller’.
Select ‘MVC 5 Controller – Empty’ on the next screen:
Give it a name of ‘GraphController’ on the next screen and click ‘Add’:
Visual studio will then create an empty controller with code that looks like the following:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCGraphApp1.Controllers { public class GraphController : Controller { // GET: Graph public ActionResult Index() { return View(); } } }
If you now look at your solution explorer, you will see that a new folder under ‘Views’ has been created called ‘Graph’. This will contain our view that will create and display a Google Bar Chart.
Right click on the ‘Graph’ folder under ‘Views’ and select ‘Add’ and then select ‘View’:
On the next screen displayed, in the text box area that says ‘View name:’ enter ‘Index’ and click the Add button at the bottom:
You should now see that a new file has been added under the ‘View/Graph’ folder called ‘Index.cshtml’. This file will contain some Javascript and HTML code that will interface with the Google Charts API and the new ‘Graph’ controller that we have created.
Right click on the ‘Index.cshtml’ file in the Solution Explorer and select ‘Set as start page’. This will make sure that when the application starts, it is directed to our ‘Index’ page which contains the code to display our Google Chart.
Next, right click on the Project (in this case ‘MVCGraphApp’) and select ‘Set as Startup Project’. This is necessary to make sure that when Visual Studio starts this web application, it knows the project file in which to find the appropriate startup files and paths.
The chart that we will be creating for our example will be a graph showing some statistics about outgoing phone calls, as if we were a telemarketing firm that wanted to track successful connections versus calls where no one answered the telephone. These will be tracked by the time of day (8:00 am to 5:00 pm).
The next step would be to create some logic in our GraphController.cs file that will return the data that we need for the chart that we are going to display in the view. For this example, I am hard-coding an object and values for demonstration purposes. In practice, this controller would contain the logic to retrieve data from whatever source is required and return the proper set of data required for the Google Chart being created and displayed. Below is the code that we are going to insert for our demonstration:
First, we’ll define our class for the data we are going to return to the view. Right click on the ‘Models’ folder in solution explorer and select ‘Add’ then select ‘Add New’:
On the next screen, select ‘Visual C#’, then select ‘Code’ and then click on ‘Class’. At the bottom of the screen key is the name of the new class container file. For this demonstration, I have named this one ‘PhoneCallInformation.cs’:
Next, click the ‘Add’ button on the bottom right.
When you open this file, the following code should be present in the PhoneCallInformation.cs file:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCGraphApp1.Models { public class PhoneCallInformation { } }
Add the class definition for our data.
namespace MVCGraphApp1.Models { public class PhoneCallInformation { public string Hour { get; set; } public int SuccessfulConnect { get; set; } public int FailedToConnect { get; set; } } }
Open the GraphController.cs’ file and add the following code:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using MVCGraphApp1.Models; namespace MVCGraphApp1.Controllers { public ActionResult Index() { return View(); } public class GraphController : Controller { // GET: Graph public ActionResult GetPhoneCallData() { PhoneCallInformation[] phoneListData = new PhoneCallInformation[] { new PhoneCallInformation() { SuccessfulConnect = 10, FailedToConnect = 5, Hour = "08:00" }, new PhoneCallInformation() { SuccessfulConnect = 9, FailedToConnect = 5, Hour = "09:00" }, new PhoneCallInformation() { SuccessfulConnect = 10, FailedToConnect = 8, Hour = "10:00" }, new PhoneCallInformation() { SuccessfulConnect = 11, FailedToConnect = 20, Hour = "11:00" }, new PhoneCallInformation() { SuccessfulConnect = 12, FailedToConnect = 12, Hour = "12:00" } }; // Return a Json object. return Json(phoneListData, JsonRequestBehavior.AllowGet); } } }
This code instantiates our class object with real data and creates a Json object to be returned to the View. It is important here to make sure that the ‘System.Web.Script.Serialization’ namespace has been included with a ‘using’ statement at the top of the file. This allows the use of the Json library. Also note that we have added a ‘using’ statement to include our ‘ViewModel’ classes: ‘MVCGraphApp1.Models’.
Now we are ready to do some work in the View. Open the view file called ‘Index.cshtml’ under the ‘Graph’ folder. The contents should look like the following:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Just below that last line in this file, add the following code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', { 'packages': ['corechart', 'table'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var dataJson; $.ajax({ url: '@Url.Action("GetPhoneCallData")', // to get the right path to controller from TableRoutes of Asp.Net MVC dataType: "json", //to work with json format type: "POST", //to do a post request contentType: 'application/json; charset=utf-8', //define a contentType of your request cache: false, //avoid caching results data: {}, // here you can pass arguments to your request if you need success: function (dataJson) { var arrOutside = new Array(); var heading = ["Hour", "Connects", "No Answer"]; arrOutside[0] = heading; for (var i = 0; i < dataJson.length; i++) { var arr = [dataJson[i].Hour, dataJson[i].SuccessfulConnect, dataJson[i].FailedToConnect]; arrOutside[i + 1] = arr; } var gdata = new google.visualization.arrayToDataTable(arrOutside); var options = { chart: { title: 'Phone Call Connections vs No Answers', subtitle: 'By Hour of day', is3D: true }, chartarea: { left: 100, top: 20, width: '75%', left:'5%', height: '100%', }, legend: { position: 'top' }, bars: 'horizontal', width: 500, height: 300, vAxis: { title: 'Time of Day', fontSize: 8 }, hAxis: { title: 'Number of Calls', fontSize: 8 }, } var chart = new google.visualization.BarChart(document.getElementById('curve_chart')); chart.draw(gdata, options); }, error: function (xhr) { alert('error' + xhr[0]); } }); } </script> <div> <table> <tr> <td id="curve_chart" style="width:500px; height:300px; float:left;"></td> </tr> </table> </div>
This code looks complicated and to some extent, unless you have read the documentation for the Google Charts API it is complicated. In general though, here is what each section does.
- This line allows the Google Charts java script code to be loaded from the Google Charts web service/repository.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
- The code below tells the system that the code that follows is going to be JavaScript. The two lines of code after that load the Google java script libraries for the type of chart we have chosen (in this case ‘corechart’) and then sets a marker with the google library that designates where the chart is to be written in our HTML.
- The next large block of code is our ‘drawChart’ function that will be executed each time the Index.cshtml file is loaded.
function drawChart() { var dataJson; $.ajax({ url: '@Url.Action("GetPhoneCallData")', // to get the right path to controller from TableRoutes of Asp.Net MVC dataType: "json", //to work with json format type: "POST", //to do a post request contentType: 'application/json; charset=utf-8', //define a contentType of your request cache: false, //avoid caching results data: {}, // here you can pass arguments to your request if you need success: function (dataJson) {
(Note: Not all code has been shown here. See the preceding pages that include the entire JavaScript method listed).
- Finally, the HTML below is needed to contain our graph on the page (DOM):
<div> <table> <tr> <td id="curve_chart" style="width:500px; height:300px; float:left;"></td> </tr> </table> </div>
When we run this MVC web solution, the following screen will be displayed:
The Google Charts methods through the Google Charts API allows for a great deal of flexibility, not only with the design of each individual chart, but also the selection of different charts that are available for use with your MVC/Web application. For more information on how the API works and what charts are available, go to: https://developers.google.com/chart/
I hope this example has been helpful in showing, in a basic way, the power of using Google Charts API in your MVC web applications. This API can truly help you to beautify your applications without a lot of detailed and time consuming software development.