Hi rani,
Using the below article i have created the example.
Here i am using Entity Framework to fetch the record from database.
For more details on Entity Framework configuration in ASP.Net Core refer below article.
Check this example. Now please take its reference and correct your code.
Model
public class Order
{
public int OrderId { get; set; }
public string ShipCity { get; set; }
public string ShipCountry { get; set; }
}
Controller
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
public IActionResult AjaxMethod([FromBody]Country country)
{
var orders = this.Context.Orders
.Where(x => x.ShipCountry == country.Name)
.GroupBy(x => x.ShipCity)
.Select(g => new
{
City = g.Key,
Count = g.Count()
});
List<object> chartData = new List<object>();
chartData.Add(new object[] { "ShipCity", "TotalOrders" });
foreach (var order in orders)
{
chartData.Add(new object[] { order.City, order.Count });
}
return Json(chartData);
}
}
public class Country
{
public string Name { get; set; }
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://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">
$(function () {
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
$('#ddlCountries').on('change', function () {
drawChart();
});
function drawChart() {
var obj = {};
obj.Name = $("#ddlCountries").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
var options = {
title: $("#ddlCountries").val() + ' City Distribution',
is3D: true
};
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r);
},
error: function (r) {
alert(r);
}
});
}
});
</script>
</head>
<body>
<table>
<tr>
<td align="center">
Country:
<select id="ddlCountries">
<option value="USA">USA</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
<option value="Brazil">Brazil</option>
</select>
</td>
</tr>
<tr>
<td>
<div id="chart" style="width: 500px; height: 400px;">
</div>
</td>
</tr>
</table>
</body>
</html>
Screenshot