How to populate google charts using data from database created via data first - ASP.Net MVC

Total Post:52

Points:366
 457  View(s)
Ratings:
Rate this:

How to populate google charts using data from database created via data first - ASP.Net MVC

Can any give me some idea that how to bind google chart with database.. thanks in advance


  1. Post:1

    Points:7
    Re: How to populate google charts using data from database created via data first - ASP.Net MVC

    Js Code

    <script type="text/javascript">
    
        google.charts.load('current', { packages: ['corechart', 'bar'] });
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            var data = '@Html.Raw(Json.Encode(@ViewBag.user))';
            var dt = new google.visualization.DataTable();
            dt.addColumn('string', 'Date');
            dt.addColumn('number', 'User');
            var data = JSON.parse(data);
            $.each(data, function (i, v) {
                dt.addRow([v.Date, v.Total]);
            });
            var options = {
                chart: {
                    title: 'Recently Registered User',
                    subtitle: 'Count',
                }
            };
            var chart = new google.visualization.ColumnChart(document.getElementById('user'));
            function selectHandler() {
                var selectedItem = chart.getSelection()[0];
                if (selectedItem) {
                    var data = dt.getValue(selectedItem.row, 0);
                    $('#myModal').modal('show');
                    alert('The user selected ' + data);
                }
            }
            google.visualization.events.addListener(chart, 'select', selectHandler);
            chart.draw(dt, options);
        }
    </script>

    View code

    <div class="canvas-chart-wrapper">
    
                              <div id="user"></div>
                        </div>

    Controller 

      ViewBag.user = _Repository.Users().Where(x => x.CreationDate >= DateTime.Now.Date.AddDays(-7)).GroupBy(x => x.CreationDate.Value.Date).Select(x => new { Total = x.Count(), Date = x.Key.ToString("dd/MM/yyyy") }).ToList();
    

    hope this helps you...

      Modified On Dec-01-2017 11:10:21 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!