Google chart with data from database

I'm facing problem in binding google chart with database.

<script type="text/javascript">

    google.charts.load("current", { packages: ["corechart"] });
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');

        data.addRows([

          ['Onions', 1],
          ['Olives', 1],
          ['Zucchini', 1],
          ['Pepperoni', 2],

        ]);

        var options = {
            title: '',
            pieHole: 0.4,
        };

        var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
        chart.draw(data, options);
    }
</script>
Last updated:12/15/2017 11:10:20 PM

1 Answers

Manish Kumar
Manish Kumar

You can bind google chart with viewbag data..

<script type='text/javascript'>

    google.charts.load('current', { packages: ['corechart', 'bar'] });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = '@Html.Raw(Json.Encode(@ViewBag.Data))';
        var dt = new google.visualization.DataTable();
        dt.addColumn('string', 'Date');
        dt.addColumn('number', 'Product');
        var data = JSON.parse(data);
        $.each(data, function (i, v) {
            // console.log(new Date(parseInt(v.Date.substr(6))).toDateString());
            dt.addRow([new Date(parseInt(v.Date.substr(6))).toDateString(), v.Total]);
        });
        var options = {
            chart: {
                title: 'Recent Record',
                subtitle: 'Count',
            }
        };

        }
    }
    google.visualization.events.addListener(chart, 'select', selectHandler);
    chart.draw(dt, options);
}

</script>

Answer