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.
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
You will need to import the following namespaces.
using System.Data;
using System.Text;
using System.Data.SqlClient;
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();
    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);
                using (SqlDataReader sdr = cmd.ExecuteReader())
                    while (sdr.Read())
                        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 = sb.Remove(sb.Length - 1, 1);
        return Content(sb.ToString());
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>
    <meta name="viewport" content="width=device-width"/>
    <table border="0" cellpadding="0" cellspacing="0">
                <select id="ddlCountries">
                    <option value="USA">USA</option>
                    <option value="Germany">Germany</option>
                    <option value="France">France</option>
                    <option value="Brazil">Brazil</option>
                <table id="rblChartType" border="0">
                        <td><input type="radio" name="ChartType" value="1" checked="checked"/>Pie</td>
                        <td><input type="radio" name="ChartType" value="2"/>Doughnut</td>
                <div id="dvChart">
                <div id="dvLegend">
    <script type="text/javascript" src=""></script>
    <script src="" type="text/javascript"></script>
    <script src="" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#ddlCountries").bind("change", function () {
            $("#rblChartType input").bind("click", function () {
        function LoadChart() {
            var chartType = parseInt($("#rblChartType input:checked").val());
                type: "POST",
                url: "/Home/AjaxMethod",
                data: { "country": $("#ddlCountries").val() },
                success: function (response) {
                    var data = eval(response);
                    var el = document.createElement('canvas');
                    //Fix for IE 8
                    if ($.browser.msie && $.browser.version == "8.0") {
                    var ctx = el.getContext('2d');
                    var userStrengthsChart;
                    switch (chartType) {
                        case 1:
                            userStrengthsChart = new Chart(ctx).Pie(data);
                        case 2:
                            userStrengthsChart = new Chart(ctx).Doughnut(data);
                    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);
                failure: function (response) {
                    alert('There was an error.');
Creating charts in ASP.Net Core