如何在MVC4中创建动态图表?

How to create a dynamic chart in MVC4?

我有一个 asp.net mvc4 应用程序,我必须在其中添加一个图表来显示数据,但浏览器中没有显示任何内容。

这是来自控制器的代码,运行良好:

    DAL dal = new DAL();
    public ActionResult Graph2(int Day)
    {
        List<Greenhouse> greenhouse = dal.FindTemperatureByDay(Day);
        return View("DynamicGraph", greenhouse);
    }

这是我的模型class温室:

public class Greenhouse
{

    [Required]
    public int Id { get; set; }
    public DateTime DateTime { get; set; }
    public double Temperature { get; set; }
    public double Humidity { get; set; }
}

这是我尝试放置图表的视图。

 @model List<Plotting.Models.Greenhouse> 
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('number','Hour');
        data.addColumn('number', 'Temperature');
        for (i = 0; i < greenhouse.length; i++) {
            data.addRow(greenhouse[i].DateTime.Hour,greenhouse[i].Temperature);
        }

        var options = {
            'title': 'Daily Report for Humidity',
            'width': 600,
            'height': 500
        };
        var chart = new google.visualization.ColumnChart(document.getElementById('chartdiv'));
        chart.draw(data, options);
    }
</script>

您应该收到错误 Uncaught Error: If argument is given to addRow, it must be an array, or null

你所在的行

data.addRow(greenhouse[i].DateTime.Hour,greenhouse[i].Temperature);

应改写为

data.addRow([greenhouse[i].DateTime.Hour,greenhouse[i].Temperature]);([]).

假设您正在将数据从服务器正确转换为 javascript。

link to jsfiddle