Charting and plotting on ASP.NET websites using the Highcharts JQuery library
There are several JQuery library’s out there to show graphs and charts on websites using JQuery. I’ve personally worked with the Highcharts library and found it to be very extensive and easy to use. Highcharts is an open source JQuery library that you can get from http://www.highcharts.com.
It’s free for non-commercial use and the extensive demo-gallery (that also includes the jquery code used to generate the different graphs) is great coding help.
Example: generating a dynamic graph with highcharts
The example code for a line, column an pie chart can found here. The example below only describes the line graph creation.
The method to create the different graphs is the same. The format of the series string may differ depending on the graph.
An example of the result when running the downloaded example
Steps on how to create the line chart example:
1. Create a new webapplication
2. Add the highcharts javascript to the solution. (They can be downloaded from http://www.highcharts.com)
3. Add a javascript file to the solution containing the code for the chart as shown below. Note that I have substituted some values with a variable name that will be filled from the ASP.Net code and replaced the code for the series with a unique string that can be searched a replaced. The reason for this is that the file contains brackets ( { } ) so the preferred method of using string.Format() to replace the hard coded values will not work.
1: var columnchart;
2: $(document).ready(function () {
3: columnchart = new Highcharts.Chart({
4: chart: {
5: renderTo: columnContainerVar,
6: defaultSeriesType: 'column'
7: },
8: title: {
9: text: columnTitleVar
10: },
11: xAxis: {
12: categories: [
13: 'Jan',
14: 'Feb',
15: 'Mar',
16: 'Apr',
17: 'May',
18: 'Jun',
19: 'Jul',
20: 'Aug',
21: 'Sep',
22: 'Oct',
23: 'Nov',
24: 'Dec'
25: ]
26: },
27: yAxis: {
28: min: 0,
29: title: {
30: text: 'Ammount'
31: }
32: },
33: tooltip: {
34: formatter: function () {
35: return '' +
36: this.x + ': €' + this.y ;
37: }
38: },
39: plotOptions: {
40: column: {
41: pointPadding: 0.2,
42: borderWidth: 0
43: }
44: },
45: series: [%seriesString%]
46: });
47:
48:
49: });
4. Add code to generate a series string. An example is shown in the code snippets below.
Support class to hold and generate valid data:
1: public class Expense
2: {
3: public int Amount { get; set; }
4: public DateTime Date { get; set; }
5:
6: public static List<Expense> GetAmountRandomAmountList()
7: {
8: Random randomizer = new Random();
9: List<Expense> result = new List<Expense>();
10: DateTime startDate = new DateTime(2009, 1, 1);
11:
12: for (int index = 0; index < 24; index++)
13: {
14: result.Add(new Expense {
15: Amount = randomizer.Next(100),
16: Date = startDate
17: });
18: startDate = startDate.AddMonths(1);
19: }
20:
21: return result;
22: }
23: }
Support function in default.aspx to set the gerated list into the correct format for the graph:
1: private string GetSeriesString()
2: {
3: List<Expense> expenses = Expense.GetAmountRandomAmountList();
4:
5: List<string> expensesLinePoints = new List<string>();
6: StringBuilder seriesString = new StringBuilder();
7:
8: foreach (Expense expenseItem in expenses)
9: {
10: expensesLinePoints.Add(expenseItem.Amount.ToString());
11:
12: if (expenseItem.Date.Month == 12)
13: {
14: if (seriesString.Length > 0)
15: {
16: seriesString.Append(",");
17: }
18: seriesString.Append("{ ");
19: seriesString.AppendFormat(@"name: {0},
20: data: [{1}]", expenseItem.Date.Year, string.Join(",", expensesLinePoints.ToArray()));
21: seriesString.Append(" }");
22:
23: expensesLinePoints = new List<string>();
24: }
25: }
26:
27: return seriesString.ToString();
28: }
5. Finally add the code to generate the graph to the Default.aspx.
1: <%@ Page Language="C#" AutoEventWireup="true"
2: CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
3:
4: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
5: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
6: <html xmlns="http://www.w3.org/1999/xhtml">
7: <head runat="server">
8: <title></title>
9: <script src="/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
10: <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
11: <script type="text/javascript" src="/Scripts/highcharts/highcharts.js"></script>
12: <script type="text/javascript" src="/Scripts/highcharts/modules/exporting.js"></script>
13: </head>
14: <body>
15: <form id="form1" runat="server">
16: <div id="linecontainer" style="width: 500px; height: 250px; margin: 0 auto">
17: </div>
18: </form>
19: </body>
20: </html>
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: // create a new stringbuilder for generating the highcharts javascript
4: StringBuilder jqueryString = new StringBuilder();
5: // create variables for simple editing of the chart.
6: // (I have substituted several hard coded settings with the variable name in the
7: // javascript file containing the code for the graph)
8: jqueryString.Append(" var lineContainerVar = 'linecontainer';");
9: jqueryString.Append(" var lineTitleVar = 'Expenses';");
10: // Read in the javascript file containing the javascript
11: // The method of using resource files makes for cleaner code and easier editing of the graph javascript
12: // Because of the use of brackets ({ }) in javascript you will find that you cannot use a string.Format()
13: // to edit the javascript in code but have to resort to creating javascript parameters and Replace()
14: jqueryString.Append(File.ReadAllText(Server.MapPath(Settings.Default.linechartlocation)));
15: // Load in the values of the graph in the format [value,value,value,value],[value,value,value,value]
16: jqueryString.Replace("[%seriesString%]", string.Concat("[", GetSeriesString(), "]"));
17: // Add the javascript to the page load to load the graph at page startup
18: Page.ClientScript.RegisterStartupScript(this.GetType(), "jquerylinechart", jqueryString.ToString(), true);
19: }
6. Run the solution.







