I am trying to implement chart.js in MVC C# but hit this error. If I load from a List, it works but if I changed to use LINQ anonymous types, it fails with error message: Uncaught TypeError: Cannot read property 'hidden' of undefined at Chart.bundle.min.js:7

My controller is

[HttpPost]
    public JsonResult NewChart()
    {

        var iData = (from p in db.Products
                      join c in db.Categories
                      on p.CategoryID equals c.CategoryID
                      group p by c.CategoryName into CatName
                      select new { Value = CatName.Key, Count = CatName.Count() }).ToList();


        //Source data returned as JSON  
        return Json(iData, JsonRequestBehavior.AllowGet);
    }

My view is

@{
    ViewBag.Title = "About";
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="myChart" width="300" height="100"></canvas>
<script>
    $.ajax({
        type: "POST",
        url: "/Home/NewChart",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (chData) {
            var aData = chData;
            var aLabels = aData[0];
            var aDatasets1 = aData[1];
            var dataT = {
                labels: aLabels,
                datasets: [{
                    label: "Test Data",
                    data: aDatasets1,
                    fill: false,
                    backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
                    borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
                    borderWidth: 1
                }]
            };
            var ctx = $("#myChart").get(0).getContext("2d");
            var myNewChart = new Chart(ctx, {
                type: 'bar',
                data: dataT,
                options: {
                    responsive: true,
                    title: { display: true, text: 'CHART.JS DEMO CHART' },
                    legend: { position: 'bottom' },
                    scales: {
                        xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }],
                        yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }]
                    },
                }
            });
        }
    });
</script>  

0 Answers