In
this article I am going to explain how to create chart using Google chart API
in MVC.
In
the previous article I have explained how to create multiselect dropdown withcheckbox using Bootstrap multiselect Jquery plugin, how to populate andvalidate Dropdowncheckboxlist custom control in asp.net and how to displaydefault text and image instead of empty cell in Angular UI-Grid.
Description:
I
want to show Indian states population on chart. Here I am using Google chart to
create chart.
Implementation:
I
have created a table tb_population and insert some dummy records.
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 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="//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
src="https://www.gstatic.com/charts/loader.js"></script>
<script
type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
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);
});
}
</script>
<fieldset>
<legend>Google Chart API tutorial</legend>
<div id="chart" style="height: 400px"></div>
</fieldset>
No comments:
Post a Comment