In this article I will explain how to implement and populate animated HTML5 Canvas Multi-Series Line Chart (Graph) 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 two ASP.Net DropDownList displaying list of Countries and an HTML DIV element to populate the HTML5 Canvas Muti-Series Line chart.
<asp:DropDownList ID="ddlCountries1" runat="server">
    <asp:ListItem Text="USA" Value="USA" Selected="True"></asp:ListItem>
    <asp:ListItem Text="Finland" Value="Finland"></asp:ListItem>
    <asp:ListItem Text="Italy" Value="Italy"></asp:ListItem>
    <asp:ListItem Text="Germany" Value="Germany"></asp:ListItem>
    <asp:ListItem Text="Mexico" Value="Mexico"></asp:ListItem>
    <asp:ListItem Text="Sweden" Value="Sweden"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlCountries2" runat="server">
    <asp:ListItem Text="USA" Value="USA"></asp:ListItem>
    <asp:ListItem Text="Finland" Value="Finland"></asp:ListItem>
    <asp:ListItem Text="Italy" Value="Italy"></asp:ListItem>
    <asp:ListItem Text="Germany" Value="Germany" Selected="True"></asp:ListItem>
    <asp:ListItem Text="Mexico" Value="Mexico"></asp:ListItem>
    <asp:ListItem Text="Sweden" Value="Sweden"></asp:ListItem>
</asp:DropDownList>
<hr />
<div id="dvChart">
</div>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
 
VB.Net
Imports System.Data
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
 
 
JSON WebMethod to populate the HTML5 Multi-Series Line Chart
The following WebMethod is used to populate the HTML5 Canvas Multi-Series Line chart. The chart will display and compare the Order statistics of two countries.
First a list of objects is created and then the distinct Years from the Orders table are added as an array of values to the list of objects. The value of Years will be displayed on X axis.
Then year wise, count of Orders for each Year is calculated for the two countries and the values added as an array to the list of objects. The list of objects now contains three objects:-
1. Array of distinct Years for populating X axis.
2. Array of value of count of Orders for each Year for the first country.
3. Array of value of count of Orders for each Year for the second country.
C#
[WebMethod]
public static List<object> GetChart(string country1, string country2)
{
    List<object> chartData = new List<object>();
    string query = "SELECT DISTINCT DATEPART(YEAR, OrderDate) Year FROM Orders";
    DataTable dtYears = GetData(query);
    List<int> labels = new List<int>();
    foreach (DataRow row in dtYears.Rows)
    {
        labels.Add(Convert.ToInt32(row["Year"]));
    }
    chartData.Add(labels);
 
    query = "SELECT DATEPART(YEAR, OrderDate) Year, COUNT(DATEPART(YEAR, OrderDate)) TotalOrders";
    query += " FROM Orders WHERE ShipCountry = '" + country1 + "' GROUP BY DATEPART(YEAR, OrderDate)";
    DataTable dtCountry1 = GetData(query);
 
    List<int> series1 = new List<int>();
    foreach (DataRow row in dtCountry1.Rows)
    {
        series1.Add(Convert.ToInt32(row["TotalOrders"]));
    }
    chartData.Add(series1);
 
    query = "SELECT DATEPART(YEAR, OrderDate) Year, COUNT(DATEPART(YEAR, OrderDate)) TotalOrders";
    query += " FROM Orders WHERE ShipCountry = '" + country2 + "' GROUP BY DATEPART(YEAR, OrderDate)";
    DataTable dtCountry2 = GetData(query);
 
    List<int> series2 = new List<int>();
    foreach (DataRow row in dtCountry2.Rows)
    {
        series2.Add(Convert.ToInt32(row["TotalOrders"]));
    }
    chartData.Add(series2);
 
    return chartData;
}
 
private static DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
        return dt;
    }
}
 
VB.Net
<WebMethod()> _
Public Shared Function GetChart(country1 As String, country2 As String) As List(Of Object)
    Dim chartData As New List(Of Object)()
    Dim query As String = "SELECT DISTINCT DATEPART(YEAR, OrderDate) Year FROM Orders"
    Dim dtYears As DataTable = GetData(query)
    Dim labels As New List(Of Integer)()
    For Each row As DataRow In dtYears.Rows
        labels.Add(Convert.ToInt32(row("Year")))
    Next
    chartData.Add(labels)
 
    query = "SELECT DATEPART(YEAR, OrderDate) Year, COUNT(DATEPART(YEAR, OrderDate)) TotalOrders"
    query += " FROM Orders WHERE ShipCountry = '" & country1 & "' GROUP BY DATEPART(YEAR, OrderDate)"
    Dim dtCountry1 As DataTable = GetData(query)
 
    Dim series1 As New List(Of Integer)()
    For Each row As DataRow In dtCountry1.Rows
        series1.Add(Convert.ToInt32(row("TotalOrders")))
    Next
    chartData.Add(series1)
 
    query = "SELECT DATEPART(YEAR, OrderDate) Year, COUNT(DATEPART(YEAR, OrderDate)) TotalOrders"
    query += " FROM Orders WHERE ShipCountry = '" & country2 & "' GROUP BY DATEPART(YEAR, OrderDate)"
    Dim dtCountry2 As DataTable = GetData(query)
 
    Dim series2 As New List(Of Integer)()
    For Each row As DataRow In dtCountry2.Rows
        series2.Add(Convert.ToInt32(row("TotalOrders")))
    Next
    chartData.Add(series2)
 
    Return chartData
End Function
 
Private Shared Function GetData(query As String) As DataTable
    Dim dt As New DataTable()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                sda.SelectCommand = cmd
                sda.Fill(dt)
            End Using
        End Using
        Return dt
    End Using
End Function
 
 
Client Side Scripting
The LoadChart method is called at two places, when page loads and when DropDownLists are changed. Inside the LoadChart method a jQuery AJAX call is made to the WebMethod and then the received JSON object is split into three JavaScript Arrays:-
1. Labels - Array of distinct Years for populating X axis.
2. Series1 - Array of value of count of Orders for each Year for first country.
3. Series2 - Array of value of count of Orders for each Year for second country.
The Labels array and the two Series arrays are set to their respective properties in the Chart.js Line chart JSON and the Chart is displayed using HTML5 Canvas.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/excanvas.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
    LoadChart();
    $("[id*=ddlCountries1], [id*=ddlCountries2]").bind("change", function () {
        LoadChart();
    });
});
function LoadChart() {
    var country1 = $("[id*=ddlCountries1]").val();
    var country2 = $("[id*=ddlCountries2]").val();
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetChart",
        data: "{country1: '" + country1 + "', country2: '" + country2 + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var labels = r.d[0];
            var series1 = r.d[1];
            var series2 = r.d[2];
            var data = {
                labels: r.d[0],
                datasets: [
                    {
                        label: country1,
                        fillColor: "rgba(255, 255, 193, 0.2)",
                        strokeColor: "#FCD209",
                        pointColor: "#FF8C00",
                        data: series1
                    },
                    {
                        label: country2,
                        fillColor: "rgba(217, 237, 247, 0.2)",
                        strokeColor: "#BCE8F1",
                        pointColor: "#0090CB",
                        data: series2
                    }
                ]
            };
            $("#dvChart").html("");
            var canvas = document.createElement('canvas');
            $("#dvChart")[0].appendChild(canvas);
 
            //Fix for IE 8
            if ($.browser.msie && $.browser.version == "8.0") {
                G_vmlCanvasManager.initElement(canvas);
            }
            var ctx = canvas.getContext('2d');
            ctx.canvas.height = 300;
            ctx.canvas.width = 500;
            var lineChart = new Chart(ctx).Line(data, {
                bezierCurve: false
            });
        },
        failure: function (response) {
            alert('There was an error.');
        }
    });
}
</script>
 
 
Screenshot
HTML5 Canvas Multi-Series Line Chart (Graph) in ASP.Net
 
 
Demo
 
 
Downloads
Download Code