Wednesday, January 25, 2017

Draw Pie chart using Google chart in MVC

In this article I am going to explain how to draw Pie chart using Google chart in MVC application.

Draw Pie chart using Google chart in MVC

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 create json action method to retrieve data from database..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Highcharts;
using DotNet.Highcharts.Helpers;
using DotNet.Highcharts.Options;
using DotNet.Highcharts.Enums;
using DotNet.Highcharts.Attributes;
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 Chartd()
            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 type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });

    function drawChart() {

        $.post('/Chart/Chartd/', {}, 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.PieChart(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