How to Create Google Charts With MVC 4

Today in this article I will show you how to create Google charts in MVC 4 in a simple way.

                                       google developer

Using JSON and MVC Razor Syntax

Since we are into development of MVC there are no server controls like RDLC charts where we drag and drop a Report Viewer to an aspx page and in C# just bind the Datasource and it works.

To overcome this kind of thing we have Google charts.

If you have already seen my Google Charts With ASP.NET Webforms than you will find them easy else you can have a look at this link:

URL: How to Create Google Charts in ASP.Net With JSON.

Since most Corporate people won't like to see data in a numbers form (Jan = 150000, FEB = 180000) we cannot visualize what is happning with numbers to overcome this so we use Charts.

Which is simple to see and understand and think about.

Example

Consider a bank having crores of transcations yearly. If he want to see 10 years of data and if you display them as numbers then he will find it difficult to understand that data.

If we have a WebMethod in ASP.NET Webforms then in MVC we have JsonResult.

webmethod

Advantages

The following are the advantages:

  • Its free to use from Google.
  • Easy to customize and design.
  • Simple to implement.

The following is the procedure:

  1. SQL Data part and Query designing.
  2. Model Design.
  3. Controller part.
  4. View part.
Are you Ready?

Let's Begin.

the requirements for Developing Google Charts in ASP.NET MVC are ASP.NET MVC, SQL Server and a reference for the Google jsapi.

SQL Data part and Query designing

In this step I will show which table I am using and which type of query I am binding to the Google Charts.

Here I have used the following 2 tables:
  • PaymentDetails
  • PlanMaster

In the PaymentDetails table I am storing all the payment related data with PlanID from the PlanMasterTable. In the PlanMaster table I am storing all Plannames.

Here I am providing a Table Snapshot view. I will provide all the tables script and data for testing.

Sql query result

Here is the query that will get the records and we will bind them to the charts.

It's a normal query I have used. In a real scenario it would have many more tables.

sql query

I have created a Stored Procedure for displaying the data.

create image query
Hey we have now completed the SQL Server part. Now we are moving to C# and ASP.NET.

This procedure is similar to my other Google charts articles because it will be easy for the developer of Webforms to use if he migrates to MVC.

How To Create Project

  • Create a New Project
  • From the Visual C# Templates select the Web option
  • After selecting Web option select ASP.NET MVC 4 Web Application.
  • Enter the name of the solution as “GoogleCharts_with_MVC4”.

Model Design

  • After creating the MVC application we will design the Model.
  • In the Model Design part I know what output I will get from the query.
  • Depending on that I have created a Class of that type.

From the above SQL Stored Procedure I will get the 2 fields as Output PlanName and PaymentAmount.

output class

Adding Folder And Class inside that folder

I will add a folder with the name ”Repo“ and Inside that folder I will add a “Class“ with name.

mydataservice.cs

In this class I will get data from the database and return a list of types Outputclass.

my data service

Code for the mydataservice Class

In this class I called the method Listdata();

  1. using GoogleCharts_with_MVC4.Models;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. namespace GoogleCharts_with_MVC4.Repo  
  6. {  
  7.     public class mydataservice  
  8.     {  
  9.         public IEnumerable Listdata()  
  10.         {  
  11.             using (SqlConnection con = new SqlConnection  
  12.                   (ConfigurationManager.ConnectionStrings["MYCON"].ToString()))  
  13.             {  
  14.                 string Query = @"SELECT  
  15.                                 pm.PlanName,  
  16.                                 SUM(p.PaymentAmount) AS PaymentAmount  
  17.                                 FROM PaymentDetails p   
  18.                                 INNER JOIN PlanMaster PM ON p.PlanID = PM.PlanID   
  19.                                 GROUP BY PM.PlanName";  
  20.                 // this is query which in in stored procedure  
  21.   
  22.                 var list = con.Query<Outputclass>("Usp_Getdata").AsEnumerable();   
  23.   
  24.                 // List of type Outputclass which it will return .  
  25.                 return list;  
  26.             }  
  27.         }  
  28.     }  
  29. }  
In this class there is a method named Listdata of Type IEnumerable.

listdata

Inside that there is a simple SQL Connection.

sql connection

Then there is string containing a SQL Query that is for refernce only because the Stored Procedure contains that query only.

string query

After Completing the String part

Here I am using the Dapper ORM for retriving data from the database. You can have other ORM or another data retreival technique.

But it should return only a list .

Here I am passing a Stored Procedure with the name “Usp_Getdata” .

connection query

And finally I will return this List.

return list

That completes the Model Design.

Controller Part

Add a new Controller with the name “DisplaychartsController”.

After adding the Controller you will see a default method with the name “Index”. This is our Main action result that will be called when we call this View().

In the next step I created JsonResult of the name Piechart .

Inside that JsonResult I have called the method with the name “Listdata();” that will return a List of type “Outputclass”.

object method

Then just return the JSON.

return list in json

Finally the Controller and View would look like this.

We have completed the Controller part now to proceed to the View part.

View Part

The View Part we will perform how to add Add the View.

In the View Part right-click inside the Controller and select Add View.

Then a new wizard will pop up.

add view

 

  • We need to create an empty view, that is why we are not selecting a model.
  • The view name would be “Index” as shown in the above Snapshot.
  • After adding “Index View” you will see a blank page with the name “Index”.

Let's start with the final step, designing the Google Charts.

In this step we will work on the View with the name “Index”.

After adding the view Index it will only contain this viewbag part in it.

  1. @{  
  2.       ViewBag.Title = "Google charts with MVC 4";  
  3.  }  
Before adding anything we first need to add a Reference of a Google script.
  1. <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  
  2.   
  3. <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
After adding the reference of Google script we will create a goblal variable of Google Charts.
  1. <script type="text/javascript">  
  2. google.load("visualization""1", { packages: ["corechart"] });  
  3. </script>  
The next step, after declaring the global varaiable, is to call JsonResult from jQuery to do that. I have created a function.
  1. <script type="text/javascript">  
  2.     $(function () {  
  3.         $.ajax({  
  4.             type: 'POST',  
  5.             dataType: 'json',  
  6.             contentType: 'application/json',  
  7.             url: '@Url.Action("Piechart")',  
  8.                 data: '{}',  
  9.                 success: function (chartsdata) {  
  10.   
  11.                     // Callback that creates and populates a data table,    
  12.                     // instantiates the pie chart, passes in the data and    
  13.                     // draws it.    
  14.   
  15.                     var data = new google.visualization.DataTable();  
  16.   
  17.                     data.addColumn('string''PlanName');  
  18.                     data.addColumn('number''PaymentAmount');  
  19.   
  20.                     for (var i = 0; i < chartsdata.length; i++) {  
  21.                         data.addRow([chartsdata[i].PlanName, chartsdata[i].PaymentAmount]);  
  22.                     }  
  23.   
  24.                     // Instantiate and draw our chart, passing in some options    
  25.                  var chart = new google.visualization.PieChart(document.getElementById('chartdiv'));  
  26.   
  27.                     chart.draw(data,  
  28.                       {  
  29.                           title: "Show Google Chart in ASP.NET",  
  30.                           position: "top",  
  31.                           fontsize: "14px",  
  32.                           chartArea: { width: '50%' },  
  33.                       });  
  34.                 },  
  35.                 error: function () {  
  36.                     alert("Error loading data! Please try again.");  
  37.                 }  
  38.             });  
  39.         })  
  40.   
  41. </script>  
This function contains the main thing, the URL "url:'@Url.Action("Piechart")'," that will call Jsonresult to declare the datatable and add columns into it.
  1. var data = new google.visualization.DataTable();  
  2. data.addColumn('string''PlanName');  
  3. data.addColumn('number''PaymentAmount');  
Then use a for loop to pass data from the Respone into the Datatable.
  1. for (var i = 0; i < chartsdata.length; i++)   
  2. {  
  3.       data.addRow([chartsdata[i].PlanName, chartsdata[i].PaymentAmount]);  
  4. }  
Instantiate and draw our chart, passing in some options as in the following:
  1. var chart = new google.visualization.PieChart(document.getElementById('chartdiv'));  
Here we pass data and other options that we need to customize the look of the charts.
  1. chart.draw(data,  
  2. {  
  3. title: "Show Google Chart in ASP.NET",  
  4. position: "top",  
  5. fontsize: "14px",  
  6. chartArea: { width: '50%' },  
  7. }); 
Here is the complete function view
  1. <script type="text/javascript">  
  2.     $(function () {  
  3.         $.ajax({  
  4.             type: 'POST',  
  5.             dataType: 'json',  
  6.             contentType: 'application/json',  
  7.             url: '@Url.Action("Piechart")',  
  8.                 data: '{}',  
  9.                 success: function (chartsdata) {  
  10.   
  11.                     // Callback that creates and populates a data table,    
  12.                     // instantiates the pie chart, passes in the data and    
  13.                     // draws it.    
  14.   
  15.                     var data = new google.visualization.DataTable();  
  16.   
  17.                     data.addColumn('string''PlanName');  
  18.                     data.addColumn('number''PaymentAmount');  
  19.   
  20.                     for (var i = 0; i < chartsdata.length; i++) 
  21.                     {  
  22.                         data.addRow([chartsdata[i].PlanName, chartsdata[i].PaymentAmount]);  
  23.                     }  
  24.   
  25.                     // Instantiate and draw our chart, passing in some options    
  26.                  var chart = new google.visualization.PieChart(document.getElementById('chartdiv'));  
  27.   
  28.                     chart.draw(data,  
  29.                       {  
  30.                           title: "Show Google Chart in Asp.net",  
  31.                           position: "top",  
  32.                           fontsize: "14px",  
  33.                           chartArea: { width: '50%' },  
  34.                       });  
  35.                 },  
  36.                 error: function () {  
  37.                     alert("Error loading data! Please try again.");  
  38.                 }  
  39.             });  
  40.         })  
  41.   
  42. </script>  
Display the Chart

The last thing is to display the chart. I used a div for this and given an id to it.
  1. <div id="chartdiv" style="width: 600px; height: 350px;">  
  2. </div>  
Final step Just Run

Now just run the application and check it.

Here comes the final output Google Charts with MVC 4. I am Loving it.

google chart with mvc4

If you need to work on other charts such as: 
  1. Columns charts
  2. Area Charts
  3. Bar Charts
  4. Scatter charts
  5. Combo charts

You need to just make the relevant changes in this part of code.

If you are developing Combo charts then you need to make changes in the Query and also DataTable of Google.

Need to add more columns.

As needed, make the change in the for Loop while adding the DataRow.

  1. var data = new google.visualization.DataTable();  
  2.   
  3. data.addColumn('string''PlanName');  
  4. data.addColumn('number''PaymentAmount');  
  5.   
  6.  for (var i = 0; i < chartsdata.length; i++) {  
  7.   data.addRow([chartsdata[i].PlanName, chartsdata[i].PaymentAmount]);  
  8.  }  
  9.   
  10.  // Instantiate and draw our chart, passing in some options    
  11.   
  12.   
  13. var chart = new google.visualization.PieChart(document.getElementById('chartdiv'));  
[ any details related Google charts use this link ]

URL: Google Charts

You can download this charts attachment and check it. You will find all the examples and related code in details.

Up Next
    Ebook Download
    View all
    Learn
    View all