Wednesday, November 23, 2011

Google chart, load on request - ASP.NET MVC 3, C# & JQuery

This is a sample to create Google chart (line chart), on request (button click or any event) with data in DataTable format using Bortosky .NET Google visualization helper.
Bortosky .NET Google visualization helper can be downloaded from here http://code.google.com/p/bortosky-google-visualization/.
UI code:
Add following script tags.
<script
src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery-1.5.1.min.js")%>"

type="text/javascript"></script>



Load google chart API
<script language="javascript" type="text/javascript"> 
     google.load("visualization", "1", { "packages": ["corechart"] });
</script>


Add a placeholder div tag for displaying the chart.
<div id="chart_div" ></div>

Button to request chart load
<input type="button" id="btnLoadChart" value="Generate Chart" />

JQuery button click event handler
$(document).ready(function () {
     $("#btnLoadChart").click(function () {
        loadChart();
    });
}

JS method to load chart, ajax call to the controller to get chart data and generate chart.
function loadChart() {

    $.ajax({
        type: "GET",
        url: "/Chart/GetChartData",
        data: "startDate=" + startDate + "&endDate=" + endDate, //pass required data to your controller

        success: function (result) {

        if (result.success) {
            var evalledData = eval("(" + result.chartData + ")");
            var opts = { width: 800, height: 300};
                new google.visualization.LineChart($("#chart_div").get(0)).draw(
new google.visualization.DataTable(evalledData, 0.5), opts);
            $('#chart_div').show();
            return false;
        }
        else {
            $('#chart_div').html('<span style="color:red;"><b>' + result.Error +                     '</b></span>');
            $('#chart_div').show();

            return false;
        }
        }
    });
    }
    return false;
}


Controller code:
 
public ActionResult GetChartData(string startDate, string endDate)
{
    try{
              //Get your data table from DB or other source
   
    DataTable chartTable = GetChartTable(startDate, endDate);

        //convert datetime value to google datetype, if your first column is date
   
    Bortosky
            .Google
            .Visualization
            .GoogleDataTable
            .SetGoogleDateType(chartTable.Columns["Date"],
                 Bortosky.Google.Visualization.GoogleDateType.Date);
         //convert DataTable to GoogleDataTable
        var googleDataTable =  
                    new Bortosky.Google.Visualization.GoogleDataTable(chartTable);
        //Pass the google datatable to UI as json string

return new JsonResult { Data = new { success = true
                        chartData = googleDataTable.GetJson() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
    }
    catch (Facebook.FacebookOAuthException ex)
    {
        return newJsonResult { Data = new { success = false,
Error = "Error generating chart!" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}


Try it out!

2 comments:

  1. Microsoft .NET Framework includes a large library and support to maintain user interface, database connectivity, web application development and network communications.The .NET Framework is intended to be used by most new applications created for the Windows platform
    http://www.nucleusoftech.com/microsoft-net.php

    ReplyDelete
  2. This is really nice article.
    http://www.aspdotnet-pools.com/2014/07/how-to-create-dynamic-google-column.html

    ReplyDelete