Sunday, 6 September 2015

jqplot integration with ASP.NET MVC

I haven't been writing for a while and it's not always easy to find time to write about interesting stuff. I must say that I wish I had enough time to post all what I have been learning for the last past years, but I will try to keep it up. Today I'm bringing you an interesting post about jqplot integration with MVC. I have been using ASP.NET for quite a while now (more than 5 years) and I hope this post could help you with the integration of jqplot as I faced some challenges that I'm resolving here.

jqplot is a plotting and charting plugin for the jQuery Javascript framework. It's very pluggable and really easy to use.

jqplot can be easily installed using Nuget package from VS:

Here is a simple example from the website:

As you could see, integration is quite simple and to plot the data, this one needs to be formatted in the format of a set [Date, value] to be displayed correctly. So here is the first challenge as we need to find a way to populate this list from our controller and then pass the correct formatted list to our jqplot function.

I'm working on an application called Flickr Photo Analytics. This application is able to connect to your Flickr stream and retrieve some useful stats that you can keep track overtime. The base application is written in Delphi and now I'm developing the web interface that goes with it using MVC. For this article I will use the examples from my source repository.

The best way to approach this problem is by creating a new ActionResult in the controller that will build the relevant data (data that we want to display and in the correct format -> [Date and Value]). Then via javascript, I will use an AJAX (Asynchronous JavaScript and XML) call to call the action method from the controller and retrieve the data in JSON format. One the data is back, I will generate the list in the correct format so jqplot can plot the data.

Here is the code from my controller:

This code loads an xml file containing some relevant data from my application and according to an id that can be passed as an argument in the url, it will return a different JSON list.

The view only needs a div with an id, in this case, chart1 that will be automatically populated with a graph by jqplot once the following javascript is loaded:

The javascript will receive the results from the JSON call in a stats variable. Once we get the whole content of the variable, we need to build the correct array that will go into jqplot. This will be done using: arr.push([new Date(date), value]):

The html is as follows (view):

Loaded units required for jqplot and the div required to display the chart.

And the final result can be seen here:

Check out the properties that I have enabled for jqplot as I've use it for quite a while and I like the way I can configure it.

Any questions, please ask!.



Post a Comment