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.
<scriptsrc="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
.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!