Charts with Asp.net MVC and jQuery through jqPlot

Asp.Net MVC is a great way to get dynamic data presented inside a web browser and thanks to the great integration of jQuery now in Visual Studio, we have many programming tools right at hand!

To show of the possibilities, I’ll give an example on how to get data from Asp.net MVC into your client jQuery code. This example will also use jqPlot to draw a dynamical graph from the given data.

First up, you’ll need to download the jqPlot plugin for jQuery from the jqPlot site: http://www.jqplot.com/ !
I have to say, this graph plugin just looks stunning and is easy enough to use with much tweaking options!!
When this is done, create your MVC project inside Visual Studio.

To get jqPlot working in your MVC project, make sure to create a subfolder jqPlot inside your Scripts folder and copy all .js files from the jqPlot download inside this subfolder!
After that, just add following inside your Site.Master page to get the correct reference to your jqPlot plugin.

Small side note, when you need to edit js files inside Visual Studio and you like to have intellisense for jQuery, be sure to add following line on top of each js file!

Next thing you’ll need to do is add a new controller inside the Controllers section. Inside this controller we will have all calls needed to get a new webpage and also for retrieving data. You add a new controller by right clicking on the Controlles folder and selecting Add>Controller! Give it a meaningful name and click OK.( in this example GraphController.cs )

Add following code inside the controller, this will give us the new web page.

Add following code inside the controller, this will present a JSON data stream back to the client. This data stream represents all markers that will be used by the jqPlot graph to draw lines ( in this example. You can also draw bar or pie charts and many other )

The class used here is called GraphData, it’s created inside the Models section and only contains 2 properties.

Now that the code is in place, right click on the HearthRate() method and select Add View. This will create a new view inside the Views section.

Edit this newly added View ( this example Views>Graph>HearthRate.aspx ) and add following code inside the asp:Content tag! This div will be used by the jqPlot, it indicates where the graph needs to be visible.

The other line is a reference to a new js file that we need for processing the JSON data and presenting it correctly to the jqPlot plugin.

Now the only thing left to do is create the js file with all the jQuery code that will process the JSON stream and draw the line chart.

With all this in place, you can start up your website and browse to the http://localhost/Graph/HearthRate site. If everything goes well, you should get following image.

asp_mvc_jqplot

[Tags]Asp.net, MVC, jQuery, jqPlot[/Tags]