C#MVC5查看动态填充的Chart.js不显示

时间:2017-05-30 16:02:24

标签: javascript c# jquery asp.net-mvc-5 chart.js

我正在尝试将chart.js库的图表实现到我的视图中。但是,我无法根据需要显示图表。

剃须刀视图中的特殊部分:

<div class="col-md-8">
            <p class="text-center">
            <strong>Energy Consumption and Production: 1 Jan, 2016 - 30 Jul, 2016</strong>
             </p>
             <div class="chart-responsive">
             <canvas id="trendChart" width="800" height="400"></canvas>
             </div> @*/.chart-responsive*@ 

关于折线图的我的Javascript代码:

$(function () {

var datachart = {
    labels: [],
    datasets: [
        {
            label: "Consumption",
            backgroundColor: "rgba(215,220,67,0.3)",
            borderColor: "rgba(220,220,220,0.7)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(220,220,220,1)",
            hoverBorderColor: "rgba(220,220,220,0.5)",
            data: []
        },
        {
            label: "Production",
            backgroundColor: "rgba(90,193,208,0.3)",
            borderColor: "rgba(151,187,205,0.7)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(151,187,205,1)",
            hoverBorderColor: "rgba(151,187,205,0.5)",
            data: []
        }
    ]
};

var trendChartOptions = {
    //Boolean - If we should show the scale at all
    showScale: true,
    //Boolean - Whether grid lines are shown across the chart
    scaleShowGridLines: false,
    //String - Colour of the grid lines
    scaleGridLineColor: "rgba(0,0,0,.05)",
    //Number - Width of the grid lines
    scaleGridLineWidth: 1,
    //Boolean - Whether to show horizontal lines (except X axis)
    scaleShowHorizontalLines: true,
    //Boolean - Whether to show vertical lines (except Y axis)
    scaleShowVerticalLines: true,
    //Boolean - Whether the line is curved between points
    bezierCurve: true,
    //Number - Tension of the bezier curve between points
    bezierCurveTension: 0.3,
    //Boolean - Whether to show a dot for each point
    pointDot: false,
    //Number - Radius of each point dot in pixels
    pointDotRadius: 4,
    //Number - Pixel width of point dot stroke
    pointDotStrokeWidth: 1,
    //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
    pointHitDetectionRadius: 20,
    //Boolean - Whether to show a stroke for datasets
    datasetStroke: true,
    //Number - Pixel width of dataset stroke
    datasetStrokeWidth: 2,
    //Boolean - Whether to fill the dataset with a color
    datasetFill: true,
    //String - A legend template
    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%=datasets[i].label%></li><%}%></ul>",
    //Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
    maintainAspectRatio: false,
    multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>",
    //Boolean - whether to make the chart responsive to window resizing
    responsive: true
};

$.getJSON("/AdminLte/GetData", function (data) {
    $.each(data, function (i, item) {
        datachart.labels.push(item._DATE);
        datachart.datasets[0].data.push(item.CONSUMPTION);
        datachart.datasets[1].data.push(item.PRODUCTION);
    })
});
var ctx = new Chart(document.getElementById("trendChart").getContext("2d")).Line(datachart, trendChartOptions);

});

我的控制器方法用于动态填充数据:

public ContentResult GetData()
        {
            List<MeterDataTrendViewModel> meterDataTrend = new List<MeterDataTrendViewModel>();
            var result =
            from s in db.MeterDatas.ToList()
            group s by new { s._DATE } into g
            select new
                {
                read_date = g.Key._DATE,
                CONSUMPTION = g.Sum(x => Convert.ToInt64(x.CONSUMPTION)),
                PRODUCTION = g.Sum(x => Convert.ToInt64(x.PRODUCTION))
                };
            foreach(var res in result)
            {
                MeterDataTrendViewModel mdv = new MeterDataTrendViewModel();
                mdv._DATE = res.read_date;
                mdv.CONSUMPTION = res.CONSUMPTION.ToString();
                mdv.PRODUCTION = res.PRODUCTION.ToString();
                meterDataTrend.Add(mdv);
            }

            return Content(JsonConvert.SerializeObject(meterDataTrend), "application/json");
        }

我已经调试了我的js代码,数据和标签数组已正确填充,因此我的控制器操作被调用。但是只有一个日期时间字符串垂直显示,所以我猜它可能与y轴对齐?

我也可以用静态数据填充图表并正确显示。我无法弄清楚为什么我的动态数据没有以正确的方式显示。

1 个答案:

答案 0 :(得分:0)

我已经设法通过以下修改自行解决了这个问题。

$.getJSON("/AdminLte/GetData", function (data) {
            $.each(data, function (i, item) {
                chartlabels[i] = item._DATE;
                cons[i] = item.CONSUMPTION;
                prod[i] = item.PRODUCTION;
            })
            var ctx = new Chart(document.getElementById("trendChart").getContext("2d")).Line(datachart, trendChartOptions);
        });
    });