As we all know there are some pretty amazing and powerful charting tools available for web developers to use, some are commercial and some are free. But a main disadvantage i saw in many of them is that, almost all of them use flash to draw graphics and manipulate settings.
But there is some pretty sleek free JQuery chart plug-ins available out there. To name a few Flot, Google Charts, jQuery Chart, jQchart, TufteGraph etc...
After a brief R&D Flot attracted me most because of its rich options set and clean, easy to use and maintainable code.
Now I will explain how to draw a simple line chart using Flot in an ASP.net web site.
I will use AJAX calls to fetch data from the server to populate chart data sets in the following example. But rather than using page methods or update panels, I will use simple JQuery AJAX post backs ($.ajax) to accomplish data retrieving tasks.
So here we go...
Let’s take a look at how Flot accepts data to draw its chart. Here is a simple JSON object which will be used to draw the chart line.
{
label: 'Europe (EU27)',
data: [[1999, 3.0], [2000, 3.9]]
}
So let’s create a class similar to this JSON object so we can serialize an object of that class to something similar.
public class Model
{
public string label;
public List<List<int>> data;
}
And let’s write a Helper class containing simple methods that can be used to serialize the Model object to a JSON object.
public static class Helper
{
private static string ToJson(this object obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, obj);
var json = Encoding.Default.GetString(ms.ToArray());
return json;
}
public static string GetJason(Model dataModel)
{
return dataModel.ToJson();
}
}
* DataContractJsonSerializer is inside the System.Runtime.Serialization.Json namespace
Now we will write a simple web method (web service method) that can be called from the client side JavaScript.
[WebMethod]
public static string GetData()
{
var dataModel = new Model {label = "Sample Chart"};
var dataList = new List<List<int>>();
for (int i = 1; i <>
{
var data = new List
dataList.Add(data);
}
dataModel.data = dataList;
return Helper.GetJason(dataModel);
}
This function will return a serialized data object like this.
{
"data":[[1,9],[2,12],[3,17],[4,24],[5,33],[6,44],[7,57],[8,72],[9,89]],
"label":"Sample Chart"
}
Now that's all from the server side. Let’s look at the client side javascript functions
In the aspx page add references to jquery.js and jquery.flot.js (download them from http://code.google.com/p/flot/downloads/list)
And inside the body add a div with the id "placeholder" to hold the chart.
add a button with the id “btnGetData” so we can fetch data upon user request
Here is the sample code to draw the chart using our predefined methods in the server side.
$(document).ready(function() {
//options that can be enabled in the chart, more options are available
var options = {
lines: { show: true },
points: { show: true },
xaxis: { tickDecimals: 0, tickSize: 1 }
};
var data = []; //data used to draw the chart
var placeholder = $("#placeholder"); //chart wrapper
$.plot(placeholder, data, options); //draw the chart
var alreadyFetched = {};
$("#btnGetData").live("click", function(e) {
var button = $(this); //get the clicked button
//execute this function after data is successfully retrieved from the ajax call
function onDataReceived(series) {
series = $.parseJSON(series.d); //get the json object (use the latest jquery script)
var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')';
button.siblings('span').text('Fetched ' + series.dabel + ', first point: ' + firstcoordinate);
if (!alreadyFetched[series.label]) {
alreadyFetched[series.label] = true;
data.push(series); //populate data
}
$.plot(placeholder, data, options); //draw the chart
}
var dataUrl = "Default.aspx/GetData"; //server method to get data
$.ajax({
type: "POST",
url: dataUrl,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onDataReceived
});
});
});
This will draw a simple line chart on your screen.
Happy charting!!!