Riquelmy Melara
Riquelmy Melara

Reputation: 941

MVC 4 with Google Charts API

I have a chart using Google Charts API, I can display information directly from my view but I want to send the information from the controller, so far I have tried to send the information as Json, The problem is that the chart is being displayed but its all gray and doesnt really shown any information, it just says Other. is there anything I am missing? my controller is

Controller:

public JsonResult GetDataAssets()
        {
            List<object> data = new List<object>();
            data.Add(new[] { "Task", "Hours per Day"});
            data.Add(new[] { "Introduction", "100" });
            data.Add(new[] { "Basic 1", "75" });
            data.Add(new[] { "PHP", "24" });
            return Json(data);
        }

and in my view I have this

View:

<script type="text/javascript">
    function drawVisualization() {


        $.post('GetDataAssets', {}, function (d) {

            var data = google.visualization.arrayToDataTable(d);

     // Create and draw the visualization.
            new google.visualization.PieChart(document.getElementById('visualization')).
                draw(data, { title: "Top Videos", pieHole: 0.4 });
        }
    )
    };

    google.setOnLoadCallback(drawVisualization);
</script>

<div  id="visualization" style="width: 600px; height: 400px; margin: auto"></div>

Upvotes: 1

Views: 5380

Answers (1)

Riquelmy Melara
Riquelmy Melara

Reputation: 941

Well, I had to rethink the way to do it, instead of sending the JSON I'm sending it to then build the chart information, Here is what I did:

Controller:

public class PieChart
{
    public string Name;
    public decimal valor;
}

public ActionResult GetData()
{
    return Json(CreateDataList(), JsonRequestBehavior.AllowGet);
}

public IEnumerable<PieChart> CreateDataList()
{
    List<PieChart> data = new List<PieChart>();
    PieChart r = new PieChart() { Name = "Introduction", valor = 20 };
    PieChart r1 = new PieChart() { Name = "Basic 1", valor = 24 };
    PieChart r2 = new PieChart() { Name = "PHP", valor = 74 };

    data.Add(r);
    data.Add(r1);
    data.Add(r2);

    return data;
}

And on the View

<script type="text/javascript">

function drawVisualization() {
    $.get('GetData', {}, function (data) {
        var tdata = new google.visualization.DataTable();

        tdata.addColumn('string', 'Year');
        tdata.addColumn('number', 'Hours');

        for (var i = 0; i < data.length; i++) {
            tdata.addRow([data[i].Name, data[i].valor]);
        }

        // Create and draw the visualization.
        new google.visualization.PieChart(document.getElementById('visualization')).
                draw(tdata, { title: "Top Videos", pieHole: 0.4 });


    })
};

google.setOnLoadCallback(drawVisualization);

</script>

Upvotes: 4

Related Questions