using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ChartTest
{
public partial class Chartnew : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public void GetTotalPhoneSales()
{
string cs = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
List<TotalSales> totalSales = new List<TotalSales>();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Sales by Year", con)
{
CommandType = CommandType.StoredProcedure
};
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
TotalSales PhoneSale = new TotalSales
{
Amount = Convert.ToDouble(rdr["Subtotal"]),
Year = Convert.ToInt32(rdr["Year"])
};
totalSales.Add(PhoneSale);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(totalSales));
}
}
class TotalSales
{
public double Amount;
public int Year;
}
}
This is the external JavaScript file.
console.log('Hello');
var chartLabel = [];
var chartData = [];
$.ajax({
alert: ("It has ended"),
url: 'Chartnew.aspx/GetTotalPhoneSales',
method: 'post',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
chartLabel.push(item.Year);
chartData.push(item.Amount);
});
},
error: function (err) {
alert(err);
}
});
var config = {
type: 'pie',
data: {
datasets: [{
data: chartData,
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: chartLabel
},
options: {
responsive: true
}
};
window.onload = function () {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
Thank you for providing codes which makes the troubleshooting more efficient.
Actually, there are some mistakes in the codes.
Miss "static" in [WebMethod] of the code behind method.
Miss <contentType: "application/json; charset=utf-8"> in ajax parameter.
Put the codes "new Chart(ctx, config)" in a wrong place.
Wrongly return the result from [WebMethod].
Wrongly fetch data from success function.
More details, you could refer to below codes.
aspx:
<form id="form1" runat="server">
<div id="canvas-holder" style="width: 40%">
<canvas id="chart-area"></canvas>
</div>
</form>
<script>
console.log('Hello');
var chartLabel = [];
var chartData = [];
$.ajax({
alert: ("It has ended"),
url: 'Chartnew.aspx/GetTotalPhoneSales',
method: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
// Get json data from d, check it from dev-tools => Press F12
data = JSON.parse(data.d);
$(data).each(function (index, item) {
chartLabel.push(item.Year);
chartData.push(item.Amount);
});
// Set the data from here
var config = {
type: 'pie',
data: {
datasets: [{
data: chartData,
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: chartLabel
},
options: {
responsive: true
}
};
// Initial Chart in ajax success function
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
},
error: function (err) {
alert(err);
}
});
window.onload = function () {
};
</script>
Code behind: (Data Simulation)
public partial class Chartnew : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetTotalPhoneSales()
{
List<TotalSales> totalSales = new List<TotalSales>();
for (int i = 0; i < 3; i++) {
TotalSales PhoneSale = new TotalSales
{
Amount = Convert.ToDouble(i+100),
Year = Convert.ToInt32(i+2020)
};
totalSales.Add(PhoneSale);
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(totalSales);
}
}
class TotalSales
{
public double Amount;
public int Year;
}
Demo:
Hope helps.
Best regards,
Sean
ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
Member
42 Points
118 Posts
Chart.Js with webmethod and data from sql server
Apr 05, 2021 04:07 AM|callykalpana|LINK
Hi
I am new to the charting feature and web methods as well. Anyhow, I have googled and I managed to come up with this, it's not working at all.
Appreciate if someone can point out what I am missing. Basically, my data is in sql server and I am trying to pull the data into a pie..( just a test I am running before I move on the real project). I found the code at this link https://stackoverflow.com/questions/54884956/pie-chart-using-chart-js-and-asp-net-web-service-asmx - I modified it with the data in my sql..
So this is the code.
This is the Chartnew.aspx page
This is the code behind page.
This is the external JavaScript file.
Contributor
3010 Points
886 Posts
Re: Chart.Js with webmethod and data from sql server
Apr 06, 2021 09:36 AM|Sean Fang|LINK
Hi callykalpana,
Thank you for providing codes which makes the troubleshooting more efficient.
Actually, there are some mistakes in the codes.
More details, you could refer to below codes.
aspx:
Code behind: (Data Simulation)
Demo:
Hope helps.
Best regards,
Sean
Member
42 Points
118 Posts
Re: Chart.Js with webmethod and data from sql server
Apr 07, 2021 07:41 AM|callykalpana|LINK
Thank you Sean Fang for pointing out the errors, I have marked yours as an answer.