In this article I will explain how to implement and populate free animated HTML5 Canvas charts from database using jQuery AJAX in ASP.Net.
The HTML 5 Canvas charts have been implemented using Chart.js library. This article also covers procedure to display the animated HTML5 chart in browsers that do not support CSS3 like IE 8.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The HTML Markup consists of an ASP.Net DropDownList with list of Countries and a RadioButtonList which will be used to switch between Pie and Doughnut chart.
There are two HTML DIV controls one to populate the HTML5 Canvas chart and other for the Chart legend.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Country:
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="USA" Value="USA" />
<asp:ListItem Text="Germany" Value="Germany" />
<asp:ListItem Text="France" Value="France" />
<asp:ListItem Text="Brazil" Value="Brazil" />
</asp:DropDownList>
<asp:RadioButtonList ID="rblChartType" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Text="Pie" Value="1" Selected="True" />
<asp:ListItem Text="Doughnut" Value="2" />
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td>
<div id="dvChart">
</div>
</td>
<td>
<div id="dvLegend">
</div>
</td>
</tr>
</table>
Namespaces
You will need to import the following Namespaces.
C#
using System.Data;
using System.Text;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Text
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
JSON WebMethod to populate the HTML5 Chart
The below WebMethod populates the data from databases and builds a JSON string that will be used to populate the HTML5 Canvas chart.
The color of the Segment of the Pie or Doughnut chart is randomly generated and added to the JSON string.
Note: Thread Sleep has been purposely added to generate Random Colors, if the delay is removed all segments of the Pie or Doughnut chart will be of same color.
C#
[WebMethod]
public static string GetChart(string country)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country);
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
while (sdr.Read())
{
sb.Append("{");
System.Threading.Thread.Sleep(50);
string color = String.Format("#{0:X6}", new Random().Next(0x1000000));
sb.Append(string.Format("text :'{0}', value:{1}, color: '{2}'", sdr[0], sdr[1], color));
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
sb.Append("]");
con.Close();
return sb.ToString();
}
}
}
}
VB.Net
<WebMethod()> _
Public Shared Function GetChart(country As String) As String
Dim constr As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Using con As New SqlConnection(constr)
Dim query As String = String.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country)
Using cmd As New SqlCommand()
cmd.CommandText = query
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
Dim sb As New StringBuilder()
sb.Append("[")
While sdr.Read()
sb.Append("{")
System.Threading.Thread.Sleep(50)
Dim color As String = [String].Format("#{0:X6}", New Random().Next(&H1000000))
sb.Append(String.Format("text :'{0}', value:{1}, color: '{2}'", sdr(0), sdr(1), color))
sb.Append("},")
End While
sb = sb.Remove(sb.Length - 1, 1)
sb.Append("]")
con.Close()
Return sb.ToString()
End Using
End Using
End Using
End Function
Client Side Scripting
The LoadChart method is called at 3 places, on load, on DropDownList change and on RadioButtonList change. Inside the LoadChart method a jQuery AJAX call is made to the WebMethod and then the received JSON string is converted to a JSON object.
The JSON object is then applied to the HTML5 Canvas chart and also used to prepare a legend for the chart by looping and adding dynamic HTML to the legend DIV.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
<script src="//cdn.jsdelivr.net/chart.js/0.2/Chart.js" type="text/javascript"></script>
<form id="form1" runat="server">
<script type="text/javascript">
$(function () {
LoadChart();
$("[id*=ddlCountries]").bind("change", function () {
LoadChart();
});
$("[id*=rblChartType] input").bind("click", function () {
LoadChart();
});
});
function LoadChart() {
var chartType = parseInt($("[id*=rblChartType] input:checked").val());
$.ajax({
type: "POST",
url: "Default.aspx/GetChart",
data: "{country: '" + $("[id*=ddlCountries]").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dvChart").html("");
$("#dvLegend").html("");
var data = eval(r.d);
var el = document.createElement('canvas');
$("#dvChart")[0].appendChild(el);
//Fix for IE 8
if ($.browser.msie && $.browser.version == "8.0") {
G_vmlCanvasManager.initElement(el);
}
var ctx = el.getContext('2d');
var userStrengthsChart;
switch (chartType) {
case 1:
userStrengthsChart = new Chart(ctx).Pie(data);
break;
case 2:
userStrengthsChart = new Chart(ctx).Doughnut(data);
break;
}
for (var i = 0; i < data.length; i++) {
var div = $("<div />");
div.css("margin-bottom", "10px");
div.html("<span style = 'display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
$("#dvLegend").append(div);
}
},
failure: function (response) {
alert('There was an error.');
}
});
}
</script>
Pie Chart
Doughnut Chart
Demo
Downloads