In this article I will explain with an example, how to implement and populate free animated HTML5 Canvas charts from database using jQuery AJAX in ASP.Net MVC Razor.
The HTML 5 Canvas charts have been implemented in ASP.Net MVC Razor 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.
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling AJAX POST operation
This Action method handles the call made from the jQuery AJAX function from the View.
Note: The following Action method handles AJAX calls and since a String value is returned, the return type is set to ContentResult. For more details refer my article Return String Content from Controller to View in ASP.Net MVC.
 
Inside this Action method, the data is populated from database and a JSON string is built which 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.
 
The JSON string is returned back to the View as String value.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ContentResult AjaxMethod(string country)
    {
        string query = "SELECT ShipCity, COUNT(OrderId)";
        query += " FROM Orders WHERE ShipCountry = @Country GROUP BY ShipCity";
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        StringBuilder sb = new StringBuilder();
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Country", country);
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    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 Content(sb.ToString());
    }
}
 
 
View
The View consists of an HTML SELECT DropDownList for selecting the Country, a set of RadioButtons for choosing the Chart type and two DIV elements, one for rendering Chart while other for rendering the legend.
The LoadChart method is called at 3 places, on load, on DropDownList selection change and on RadioButton selection change.
Inside the LoadChart method, the URL for the jQuery AJAX call is set to the Controller’s action method i.e. /Home/AjaxMethod and when the jQuery AJAX call is made to the Controller’s Action method, the received JSON string response 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.
Note: For more details on using jQuery AJAX in ASP.Net MVC, please refer my article ASP.Net MVC: Call Controller Method from View using jQuery AJAX.
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Country:
                <select id="ddlCountries">
                    <option value="USA">USA</option>
                    <option value="Germany">Germany</option>
                    <option value="France">France</option>
                    <option value="Brazil">Brazil</option>
                </select>
                <table id="rblChartType" border="0">
                    <tr>
                        <td><input type="radio" name="ChartType" value="1" checked="checked"/>Pie</td>
                        <td><input type="radio" name="ChartType" value="2"/>Doughnut</td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>
                <div id="dvChart">
                </div>
            </td>
            <td>
                <div id="dvLegend">
                </div>
            </td>
        </tr>
    </table>
    <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>
    <script type="text/javascript">
        $(function () {
            LoadChart();
            $("#ddlCountries").bind("change", function () {
                LoadChart();
            });
            $("#rblChartType input").bind("click", function () {
                LoadChart();
            });
        });
        function LoadChart() {
            var chartType = parseInt($("#rblChartType input:checked").val());
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: "{country: '" + $("#ddlCountries").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function (response) {
                    $("#dvChart").html("");
                    $("#dvLegend").html("");
                    var data = eval(response);
                    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>
</body>
</html>
 
 
Screenshot
Implement Free Charts using Charts.js in ASP.Net MVC Razor
 
 
Downloads