In this article I will explain with an example, how to create Doughnut Chart using
ChartJS with
AJAX in ASP.Net with C# and VB.Net.
The HTML5 Canvas charts have been implemented using
Chart.js library to which
JSON object is supplied as source of data.
ChartJS plugin
Please refer the following link for documentation for the
jQuery ChartJS plugin.
Database
I have made use of the following table FruitChart with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of following element:
canvas – For displaying chart.
<canvasid="dvChart"></canvas>
Namespaces
You will need to import the following namespaces.
C#
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
Generating JSON string for the Chart using WebMethod
Inside the
WebMethod, the records are fetched from the
FruitChart Table of
SQL Server database using
DataReader.
Then, inside the WHILE loop, a JSON string is generated with following properties:
Name – This property will be displayed in Labels.
Popularity – This property will be used to populate the Chart.
Color – This property will be used to set the color of the various sections of the Chart.
Finally, the JSON string is returned, which will be used inside the
JavaScript function for populating the Chart.
C#
[WebMethod]
public static string GetChartData()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sql = "SELECT Name, Popularity, Color FROM FruitChart";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
string data = "[";
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
data += "{";
data += string.Format("Name : '{0}', Popularity : {1}, Color : '{2}'", sdr["Name"], sdr["Popularity"], sdr["Color"]);
data += "}, ";
}
data = data.Remove(data.Length - 1, 1);
data += "]";
}
con.Close();
return data;
}
}
}
VB.Net
<WebMethod>
Public Shared Function GetChartData() As String
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql AsString = "SELECT Name, Popularity, Color FROM FruitChart"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
con.Open()
Dim data As String = "["
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
data += "{"
data += String.Format("Name : '{0}', Popularity : {1}, Color : '{2}'", sdr("Name"), sdr("Popularity"), sdr("Color"))
data += "}, "
End While
data = data.Remove(data.Length - 1, 1)
data += "]"
End Using
con.Close()
Return data
End Using
End Using
End Function
Populating Chart using JSON data
Inside the HTML Markup, the following script files are inherited.
1. jquery.min.js
2. chart.umd.min.js
Inside the
jQuery document ready event handler, an
AJAX call is made to the
GetChartData WebMethod (explained earlier), which returns the JSON string based on which the Chart will be displayed.
Then, inside the Success event handler, the PopulateChart function is called.
The
PopulateChart JavaScript function accepts two parameters:
1. JSON object – The JSON string received from Server-Side (Code-Behind) is converted to JSON object.
2. Chart type – The type of chart.
PopulateChart JavaScript function
Inside this function, the canvas element is referenced and passed as parameter to the Chart object of the Chart.js library.
Then, the following other properties are set:
type – the type of Chart.
data – here the JSON data is mapped with Chart data. Labels are mapped with
Inside the labels the
Name property of the
JSON object is set.
For datasets, the following properties i.e data, backgroundColor, borderColor, borderWidth are set.
Finally, the legends are defined and the Chart is populated.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<canvas id="dvChart"></canvas>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetChartData",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
PopulateChart(eval(r.d), 'doughnut');
},
error: function (response) {
alert(response.responseText);
}
});
});
function PopulateChart(chartData, chartType) {
var dvChart = $('#dvChart');
var chart = new Chart(dvChart, {
type: chartType,
data: {
labels: chartData.map(fruit => fruit.Name),
datasets: [{
data: chartData.map(fruit => fruit.Popularity),
backgroundColor: chartData.map(fruit => fruit.Color),
borderColor: ['#FFF'],
borderWidth: 1
}]
},
options: {
plugins: {
legend: {
labels: {
boxWidth: 10, // Width of legend box
boxHeight: 10 // Height of legend box
},
display: true, // Show hide legends
position: 'right', //'left', 'right', 'top', 'bottom'
align: 'center', // 'start', 'center', 'end'
reverse: false // Reverse order
}
}
}
});
};
</script>
Screenshot
Demo
Downloads