Hi rani,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxMethod()
{
string query = "SELECT ShipCity, COUNT(orderid) TotalOrders";
query += " FROM Orders WHERE ShipCountry = 'USA' GROUP BY ShipCity";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
List<object> chartData = new List<object>();
chartData.Add(new object[] { "ShipCity", "TotalOrders" });
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[] { sdr["ShipCity"], sdr["TotalOrders"] });
}
}
con.Close();
}
}
return Json(chartData);
}
}
View
<div ng-app="MyApp" ng-controller="MyController">
<div id="chart" style="width: 500px; height: 400px;">
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.3.0/angular.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http) {
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(function () {
$http.post("Home/AjaxMethod", { headers: { 'Content-Type': 'application/json'} })
.then(function (r) {
var data = google.visualization.arrayToDataTable(r.data);
var options = {
title: 'USA City Distribution',
is3D: true
};
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
}, function (response) {
$window.alert(response.responseText);
});
});
});
</script>
Screenshot