Thursday, December 15, 2016

Google chart: create chart in MVC

In this article I am going to explain how to create chart using Google chart API in MVC.

how to create chart using Google chart API in MVC

I want to show Indian states population on chart. Here I am using Google chart to create chart.

I have created a table tb_population and insert some dummy records.

public partial class Tb_Population
        public int Id { get; set; }
        public string StateName { get; set; }
        public Nullable<long> TotalPopulation { get; set; }

Add controller
Add new empty controller to project and json action.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;
using System.Web.WebPages.Html;
using System.Web.Mvc.Html;

namespace MVC_Project.Controllers
    public class ChartController : Controller
        DemoEntities1 db = new DemoEntities1();
        // GET: /Chart/
        public ActionResult Index()
            return View();
        public JsonResult Chart()
            var data = db.Tb_Population.ToList();
            return Json(data,JsonRequestBehavior.AllowGet);


Add view
Add view for index action.

Complete code of index.cshtml:
    ViewBag.Title = "Google Chart API";

<script type="text/javascript" src="//"></script> 
<script type="text/javascript" src=""></script>
<script src=""></script>

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });

    function drawChart() {

        $.post('/Chart/Chart/', {}, function (data) {
            var dt = new google.visualization.DataTable();

            dt.addColumn('string', 'StateName');
            dt.addColumn('number', 'TotalPopulation');

            for (var i = 0; i < data.length; i++) {
                dt.addRow([data[i].StateName, data[i].TotalPopulation]);

            var options = {
                title: "State wise Population",
                is3D : true

            var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
            chart.draw(dt, options);

    <legend>Google Chart API tutorial</legend>
    <div id="chart" style="height: 400px"></div>

No comments:

Post a Comment