Showing posts with label Google Chart. Show all posts
Showing posts with label Google Chart. Show all posts

Sunday, 14 July 2013

Google Charts with MVC3


In this blog I am going to talk about how to add the powerfull Google Charts to your asp.net MVC 3 Application. Google Chart Tools provide a perfect way to visualize data on your website. From simple line charts to complex hierarchical tree maps, the chart galley provides a large number of well-designed chart types. Populating your data is easy using the provided client- and server-side tools.

Step 1: Create a new project

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application

Step 2:Javascript files and libraries

add the following javascript files to head of your page
?
1
2
<script type="text/javascript" src="/Scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Step 3: Add Client Javascript and Html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script type="text/javascript">
       google.load("visualization", "1", { packages: ["corechart"] });
       google.setOnLoadCallback(drawChart);
       function drawChart() {
           $.get('/Home/GetData', {},
   function (data) {
       var tdata = new google.visualization.DataTable();
 
       tdata.addColumn('string', 'Year');
       tdata.addColumn('number', 'Salary');
       tdata.addColumn('number', 'Expense');
 
       for (var i = 0; i < data.length; i++) {
           tdata.addRow([data[i].Year, data[i].Salary, data[i].Expense]);
       }
 
       var options = {
           title: "Expenses, Salary For the current year"
       };
 
       var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
       chart.draw(tdata, options);
   });
       }
   </script>
?
1
2
<div id="chart_div" style="width: 900px; height: 500px;">
      </div>
Note here we are making an ajax request to “/Home/GetData” to get data from server and assign data to google chart api

Step 4: Add ServerSide

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class HomeController : Controller
  {
      //
      // GET: /Home/
 
      public ActionResult Index()
      {
          return View();
      }
 
      public ActionResult GetData()
      {
          return Json(CreateCompaniesList(), JsonRequestBehavior.AllowGet);
      }
 
      private IEnumerable<Company> CreateCompaniesList()
      {
          List<Company> companies = new List<Company>();
 
          Company company = new Company() {  Expense = 200, Salary = 1000, Year = new DateTime(2012, 1, 1).ToString("yyyy/MM") };
          Company company1 = new Company() {  Expense = 300, Salary = 1100, Year = new DateTime(2012, 2, 1).ToString("yyyy/MM") };
          Company company2 = new Company() {  Expense = 240, Salary = 1200, Year = new DateTime(2012, 3, 1).ToString("yyyy/MM") };
          Company company3 = new Company() {  Expense = 100, Salary = 1300, Year = new DateTime(2012, 4, 1).ToString("yyyy/MM") };
          Company company4 = new Company() {  Expense = 40, Salary = 1100, Year = new DateTime(2012, 5, 1).ToString("yyyy/MM") };
          Company company5 = new Company() { Expense = 500, Salary = 1300, Year = new DateTime(2012, 6, 1).ToString("yyyy/MM") };
 
          companies.Add(company);
          companies.Add(company1);
          companies.Add(company2);
          companies.Add(company3);
          companies.Add(company4);
          companies.Add(company5);
 
          return companies;
      }
  }
That’s all. You can download the sample from here

Load Google Chart by Ajax using Asp.net MVC and jQuery


If you are looking for a modern chart tool in a modern browser, you must not not to know the free one that offer by Google – Google Chart, is a HTML5/SVG technology to provide cross-browser compatibility (including VML for older IE versions) and cross platform portability to iPhones, iPads and Android. No plugins are needed. Don’t get confused by the image chart offered by Google, which was another chart tool. Now the new HTML5 Google chart provides more interaction and better rendering to users .googlechartaspnetmvc I found it’s very easy to use Google chart with Asp.Net MVC. Especially, the View allow you to control the way you want the html being rendered. Compares to the Asp.net chart tool offered by Microsfot which works the best with original asp.net web form . is also workable with Asp.net MVC. However, the Google offer an elegant and modern way to render a chart for web application. In this tutorial, it demonstrates how to load the data to Google chart dynamically(ajax) using jquery instead of from render data on the page itself. In the javascript below, it calls /googlechart/getPieChartData to get the data in json format and then add each element of json into the Google’s DataTable. Therefore, the view only contains the html, javascript and some static content such as header column label and the name of the chart. And the ajax call from jquery does the job retrieving data from server side. You may ask, what’s benefit of doing in this way compares to the traditional image chart. It’s more dynamic (because of HTML5), it provides better user experience by reducing the load time (less html to browser) or by show a loading image before Google chart is fully loaded.




























<script type="text/javascript" src="/Scripts/jquery-1.5.1.min.js"></script><script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">// <![CDATA[
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
 
function drawChart() {
 
$.post('/googlechart/getPieChartData', {},
function (data) {
var tdata = new google.visualization.DataTable();
 
tdata.addColumn('string', 'Country');
tdata.addColumn('number', 'Population');
 
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Value]);
}
 
var options = {
title: "Top 5 Country's Population"
};
 
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(tdata, options);
});
 
}
// ]]></script>
On the server side, create a action that return data in Json format with Name and Value fields.
1
2
3
4
5
6
7
8
9
10
11
public JsonResult GetPieChartData()
{
 
var data = new[] { new { Name = "China", Value = 1336718015 },
new { Name = "India", Value = 1189172906 },
new { Name = "United States", Value = 313232044 },
new { Name = "Indonesia", Value = 245613043 },
new { Name = "Brazil", Value = 203429773 },};
 
return Json(data);
}