According to the chart.js documentation you are supposed to be able to create a chart data object, populate it, and pass that to the chart object and have it render. I am stuck and not sure what I have done incorrectly. The data is getting to the front end, however it must not be formatted in the way that the chart.js object wants it. I have searched and cannot find anything on this. There are no errors thrown on the client side, and I can see the data just fine in the debugger. Also, as you see in this example I have tried to stringify the data as well, still to no avail.
http://www.chartjs.org/docs/#chart-configuration-chart-data
This is the simple class that I created to represent what the documentation states:
public class ChartData
{
public object[] datasets { get; set; }
public string[] labels { get; set; }
public string[] xLabels { get; set; }
public string[] yLabels { get; set; }
}
Here is the Controller method:
public JsonResult GetChartData()
{
List<MyClass> myData = db.MyClass
.Where(o => o.Category == "SomeValue")
.ToList();
ChartData cData = new ChartData();
cData.datasets = new object[2];
cData.labels = new string[myData.Count];
string[] ds1 = new string[myData.Count];
string[] ds2 = new string[myData.Count];
for (int i = 0; i < myData .Count; i++)
{
cData.labels[i] = myData [i].Months;
ds1[i] = myData[i].SomeCount.ToString();
ds2[i] = myData[i].AnotherCount.ToString();
}
cData.datasets[0] = ds1;
cData.datasets[1] = ds2;
return Json(new
{
data = cData
},
JsonRequestBehavior.AllowGet);
}
This is the javascript on the client side that is calling the controller and trying to display the data:
function getChartData() {
$.ajax({
type: "POST",
url: "GetChartData",
data: "{}",
dataType: "json",
cache: true,
success: function (Result) {
drawChart(JSON.stringify(Result.data));
},
error: function (Result) {
alert("Error");
}
});
}
function drawChart(data) {
// render chart
var ctx = document.getElementById("lineChart").getContext("2d");
var chartInstance = new Chart(ctx,
{
type: 'line',
data: data,
options: lineOptions
});
};