In this article I will explain with an example, how to implement and populate charts from database using jQuery AJAX in ASP.Net Core MVC.
The HTML 5 Canvas charts have been implemented in ASP.Net Core MVC using Chart.js library.
This article will illustrate how to display the animated HTML5 chart in browsers that do not support CSS3 like IE 8.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
 
 

Namespaces
You will need to import the following namespaces.
using System.Data;
using System.Text;
using System.Data.SqlClient;
 
 
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.
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 using Content function.
Note: For more details on using Content function in ASP.Net Core MVC, please refer my article Using ContentResult in ASP.Net Core MVC.
 
public class HomeController : Controller
{
    // GET: Home
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult AjaxMethod(string country)
    {
        string query = "SELECT ShipCity, COUNT(OrderId)";
        query += " FROM Orders WHERE ShipCountry = @Country GROUP BY ShipCity";
        string constr = @"Data Source=.\SQL2019;Initial Catalog=northwind;integrated security=true";
        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 Core MVC, please refer my article ASP.Net Core: jQuery AJAX and JSON Example in ASP.Net Core MVC.
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</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="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
    <script src="https://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() },
                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
Creating charts in ASP.Net Core
 
 
Downloads