Display Google Pie Chart in MVC C# Ajax Services
In The Section, We See about Google Pie Chart Loading Data From SQL Server Database. Using MVC Ajax Service to Get The Data and Load to Google PieCharts.
SQL Table:
Controller
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Chartsprojects.Controllers
{
public class GoogleChartsController : Controller
{
public ActionResult GooglePieCharts()
{
return View();
}
public class Det
{
public int Id;
public String Name;
public decimal yVal;
}
public JsonResult DispRec()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["blogger"].ToString());
List<Det> obj = new List<Det>();
cn.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter("select * from mGoogleChartData", cn);
da.Fill(dt);
cn.Close();
foreach (DataRow dr in dt.Rows)
{
Det def = new Det();
def.Id = Convert.ToInt32(dr[0].ToString());
def.Name = dr[1].ToString();
def.yVal = Convert.ToDecimal(dr[2].ToString());
obj.Add(def);
}
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
}
View Code:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GooglePieCharts</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<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() {
$.ajax({
cache: false,
async: false,
type: "POST",
dataType: "Json",
contentType: "application/json; charset=utf-8",
url: "/GoogleCharts/DispRec",
// data: {},
success: function (data) {
var len = data.length;
var gldata = new google.visualization.DataTable();
gldata.addColumn('string', 'name');
gldata.addColumn('number', 'yVal');
for (var i = 0; i < len; i++) {
gldata.addRow([data[i].Name, data[i].yVal]);
}
var options = {
title: 'Product'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(gldata, options);
},
error: function (result) {
console.log(result);
}
});
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Comments
Post a Comment
Thank You for your Comment