Maria
Maria

Reputation: 313

How to create a dynamic chart in MVC4?

I have an asp.net mvc4 application in which i have to add a chart to display the data ,but nothing appears in the browser.

Here is the code from the controller which works good:

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

Here is my model class 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; }
}

And here is the view that I tried to put the chart .

 @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>

Upvotes: 0

Views: 324

Answers (1)

Henrik Aronsson
Henrik Aronsson

Reputation: 1413

You should be recieving the error Uncaught Error: If argument is given to addRow, it must be an array, or null.

Your row

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

should be rephrased to

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

Assuming you are converting your data from the server to javascript correctly.

link to jsfiddle

Upvotes: 1

Related Questions