I am trying to create charts using Chart Js in my asp.net application. I am fetching data from code database and and generating the string as per the documentation in back end. And then i am calling that web method to fetch the chart data and render it on page.
function LoadVarianceChart() {
var data;
$.ajax({
type: "POST",
url: "Analysis.aspx/GetVarianceChart",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dvVarianceChart").html("");
var obj = r.d;
console.log(obj);
data = obj;
var el = document.createElement('canvas');
$("#dvVarianceChart")[0].appendChild(el);
//Fix for IE 8
if ($.browser.msie && $.browser.version == "8.0") {
G_vmlCanvasManager.initElement(el);
}
var ctx = el.getContext('2d');
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var userStrengthsChart;
userStrengthsChart = new Chart(ctx).Bar(data);
},
failure: function (response) {
alert('There was an error.');
}
});
}
Here is my c# web method.
[WebMethod]
public static string GetVarianceChart()
{
DataSet ds = Utility.ExecuteDataTable("GetAdvarienceByBrandFamily", null);
VarianceChartModel bar = new VarianceChartModel();
bar.labels = ds.Tables[0].Rows[0][0].ToString().Split(',');
bar.datasets = new List<datasets>();
for (int i = 1; i < ds.Tables.Count; i++)
{
datasets dataset = new datasets();
dataset.data = Array.ConvertAll(ds.Tables[i].Rows[0][0].ToString().Split(','), decimal.Parse);
dataset.label = "new";
dataset.fillColor = "rgba(220,220,220,0.5)";
dataset.highlightFill = "rgba(220,220,220,0.75)";
dataset.highlightStroke = "rgba(220,220,220,1)";
dataset.strokeColor = "rgba(220,220,220,0.8)";
bar.datasets.Add(dataset);
}
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
var writer = new JsonTextWriter(stringWriter);
writer.QuoteName = false;
serializer.Serialize(writer, bar);
writer.Close();
var json = stringWriter.ToString();
return json.ToString();
}
}
Here my web method is generating the string correctly as per the documentation. If i use the generated string statically in chart js then the chart is getting generated correctly. But when i try to provide the same string by calling the back end method then it gives me Uncaught TypeError: Cannot read property 'length' of undefined
I am not sure why it is behaving like this for the same string. Is this something related to C# string and java script string compatibility ?
I figured out this problem. Here is the code which lets you create a chart by getting data from database using asp.net.
Here is the web method which provides data to charts.