Search code examples
jsonasp.net-mvcgoogle-visualizationdonut-chart

how to draw a google pie (or donut) chart with data from database


I want to draw a pie or donut chart on my MVC project. I can draw it without database. But I want to draw it with data from database. How can I do that?

Here is my sample code for donut chart without database:

<html>
<head>
    <title>Chart</title>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load("current", { packages: ["corechart"] });
        google.charts.setOnLoadCallback(drawChart);
        function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['Task', 'Hours per Day'],
              ['Work', 11],
              ['Eat', 2],
              ['Commute', 2],
              ['Watch TV', 2],
              ['Sleep', 7]
            ]);

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

            var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>

Solution

  • You basically need to generate the data similar to your javascript array in your action method and pass that to your view. I have hard coded it here. But you may replace it with data from your db.

    public ActionResult Index()
    {
        var data = new List<List<object>>()
        {
            new List<object>
            {
                "Task","Hours per day"
            },
            new List<object>
            {
                "Work",45
            }
            ,
            new List<object>
            {
                "Eat",25
            },
            new List<object>
            {
                "Commute to work",30
            }
        };
        return View(data);
    }
    

    Now your view will be strongly typed to List<List<object>>

    @model List<List<object>>
    

    Now in the same view's script section, serialize your model to a js variable(array) and use that as the input to the arrayToDataTable method.

    var dataArr = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
    var data = google.visualization.arrayToDataTable(dataArr);