Tags

, , , , , ,

The following are the set of lightweight charting libraries that work perfectly in a standard HTML/JavaScript/CSS project and in an MVC 5 application. I’ve posted a description of how to solve the problems I encountered doing the latter.

amCharts
The amCharts download includes the core amcharts.js file, a .js file for each chart type and plugins for additional features. Given the download size and the number of files, I recommend manually copying just the relevant files instead of installing amCharts as a NuGet package.

amcharts

The following screenshot gives an example of how customisable each chart is:

amcharts-code-view

Chart.js
The simplest and cleanest charting library of the four I’ve tried, and it’s extensively documented. This requires only the Chart.js file, the code for implementing the charts is relatively lightweight and it uses HTML5’s canvas feature for the rendering. Chart.js is ideal for dashboard applications that don’t require too much detail or granularity.

chartjs

Highcharts
Although Highcharts is installable as a NuGet package, it’s probably best to just copy the single Highcharts.js file to the Scripts directory. Apart from that file, only jQuery is required. Highcharts is probably the better option for rendering large detailed graphs.

highcharts

jqPlot
Based on jQuery, jqPlot has a collection of very small .js files, each for rendering a different chart type – the developer only includes the files that are needed. The main jquery.jqplot.js file is almost 500KB, though.

jqplot

Data Access
So, the question now is not how we get chart applications to read from a database, but instead how to get the database column values into a JavaScript array. The first stage of this is to use C# methods to get whatever data as an array from the database. Secondly, pass that array to a JavaScript section in the view layer.

amCharts: chartData = [{x,y}, {x,y}, {x,y}, {x,y}];
Chart.js: datasets: [{data: [a, b, c, d]}]
Highcharts: series: [ { name: 'firstSeries', data: [a, b, c, d] } ]
jqPlot: chartData = [[a, b, c, "firstSet"], [a, b, c, "secondSet"], [a, b, c, "thirdSet"];

Fixing jqPlot and other JavaScript API Problems in MVC
Quite a few questions were posted on Stack Overflow about the runtime errors while using JavaScript in MVC 5: ‘Unable to get property ‘value’ of undefined or null reference’ (0x800a138f)‘ and ‘JavaScript runtime error: ‘jQuery’ is undefined’ (0x800a1391)‘.

Here’s the solution: First, make sure the latest jQuery and jqPlot (or whichever library) files are installed. Also, read the usage file included in the Scripts folder for jqPlot.
Next, import the external .js libraries in the following format instead of using @Script.Render:

jqplot-js-imports-2

Then remove the ‘$(document).ready(function()‘ from the embedded JavaScript, and retain only the code contained by it, as it conflicts with what MVC already does. For example, my graph rendering code is:

jqplot-code-view

Advertisements