In
this article I am going to explain how to draw Pie chart using Google chart in
MVC application.
In
previous article I have explained how to Check Case-Sensitivity in SQL Server, howto create comma separated list in Sql server and how to Encrypt storeprocedure, view and function in sql server.
Implementation:
Model
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="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
type="text/javascript" src="https://www.google.com/jsapi"></script>
<script
type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
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);
});
}
</script>
<fieldset>
<legend>Google Chart API tutorial</legend>
<div id="chart" style="height: 400px"></div>
</fieldset>
No comments:
Post a Comment