---
title: "How to populate google charts using data from database created via data first - ASP.Net MVC"  
description: "How to populate google charts using data from database created via data first - ASP.Net MVC"  
author: "Manish Kumar"  
published: 2017-11-30  
updated: 2023-06-18  
canonical: https://www.mindstick.com/forum/34370/how-to-populate-google-charts-using-data-from-database-created-via-data-first-asp-dot-net-mvc  
category: "asp.net mvc"  
tags: ["c#", "linq", "asp.net mvc", "mvc"]  
reading_time: 4 minutes  

---

# How to populate google charts using data from database created via data first - ASP.Net MVC

How to [populate](https://www.mindstick.com/blog/60/populate-records-in-second-listbox-according-to-the-selection-in-first-list-box) [google](https://www.mindstick.com/articles/43833/google-lighthouse-and-how-is-it-changing-the-way-we-development-and-design-websites) [charts](https://www.mindstick.com/articles/157141/understanding-bar-charts-and-column-charts) using [data from database](https://www.mindstick.com/forum/34402/google-chart-with-data-from-database) created via data first - [ASP.Net MVC](https://www.mindstick.com/forum/155798/what-is-caching-in-asp-dot-net-mvc)

Can any give me some idea that how to bind google [chart](https://www.mindstick.com/articles/1509/show-google-analytics-data-in-chart-in-asp-dot-net-mvc) with database.. thanks in [advance](https://www.mindstick.com/blog/33258/jee-mains-and-jee-advance-exams)

\

## Replies

### Reply by Aryan Kumar

Sure, here are the steps on how to populate Google Charts using [data](https://www.mindstick.com/articles/13050/salesforce-aiming-to-dominate-predictive-analytics-with-data-science) from a [database](https://www.mindstick.com/articles/12226/use-of-database-in-sencha-extjs-and-insert-record-from-user-form-using-ajax) created via data first in [ASP.NET](https://www.mindstick.com/articles/934/default-folders-available-inside-the-asp-dot-net-application-folder) MVC:

1. Create a model class that represents the data that you want to display in the chart.
2. Create a controller action that gets the data from the database and returns it as a JSON object.
3. Create a view that renders the chart and passes the JSON object to the chart.
4. Use the Google Charts API to create the chart.

Here is an example of how to populate Google Charts using data from a database created via data first in ASP.NET MVC:

C#

```plaintext
public class ProductModel
{
  public int ProductId { get; set; }
  public string ProductName { get; set; }
  public int QuantitySold { get; set; }
}

public class ProductController : Controller
{
  public ActionResult GetProducts()
  {
    // Get the products from the database.
    var products = new List<ProductModel>();
    products.Add(new ProductModel { ProductId = 1, ProductName = "Product 1", QuantitySold = 10 });
    products.Add(new ProductModel { ProductId = 2, ProductName = "Product 2", QuantitySold = 20 });
    products.Add(new ProductModel { ProductId = 3, ProductName = "Product 3", QuantitySold = 30 });

    // Return the products as a JSON object.
    return Json(products);
  }
}
```

This code will create a model class that represents the product data. The model class has three properties: ProductId, ProductName, and QuantitySold.

The controller action GetProducts() gets the products from the database and returns them as a JSON object. The JSON object will contain the product data in a format that can be used by Google Charts.

The view that renders the chart should have a chart that is created using the Google Charts API. The chart should be bound to the JSON object that is returned by the controller action.

For example, the following code shows how to render a chart in a view:

HTML

```plaintext
<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() {
    // Create the chart.
    var data = google.visualization.arrayToDataTable([
      ["Product", "Quantity Sold"],
      ["Product 1", 10],
      ["Product 2", 20],
      ["Product 3", 30],
    ]);

    // Create the chart options.
    var options = {
      title: "Products Sold",
      hAxis: {
        title: "Product",
      },
      vAxis: {
        title: "Quantity Sold",
      },
    };

    // Create the chart.
    var chart = new google.visualization.BarChart(document.getElementById("chart"));

    // Draw the chart.
    chart.draw(data, options);
  }
</script>

<div id="chart"></div>
```

This code will create a bar chart that displays the quantity of products sold. The chart is bound to the JSON object that is returned by the controller action.

### Reply by Anonymous User

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...


---

Original Source: https://www.mindstick.com/forum/34370/how-to-populate-google-charts-using-data-from-database-created-via-data-first-asp-dot-net-mvc

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
