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

时间:2015-07-27 22:10:03

标签: c# asp.net asp.net-mvc asp.net-mvc-4 google-visualization

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

以下是来自控制器的代码:

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

这是我的模型类Greenhouse:

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>

1 个答案:

答案 0 :(得分:1)

您应该收到错误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