Topic: How to display Google Pie Chart from database on DropDownList selection in ASP.Net Core MVC
public
IActionResult AjaxMethod(
string
country)
{
string
query =
"SELECT ShipCity, COUNT(orderid) TotalOrders"
;
query +=
" FROM Orders WHERE ShipCountry = '"
+country+
"' GROUP BY ShipCity"
;
string
constr = ConfigurationManager.ConnectionStrings[
"Constring"
].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);
}
ANANYA
1
2
3
4
5
6
public class Order
{
public int OrderId { get; set; }
public string ShipCity { get; set; }
public string ShipCountry { get; set; }
}
Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 chartData = new List();
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; }
}
PARTH
Prerequisites
Install Visual studio 2017 updated any version
Install .Net core SDK 2.1 or above
Step 1- Create an ASP.NET Core 2.1 MVC Project
Open Visual Studio and select File -> New -> Project.
After selecting the project, a "New Project" dialog will open. Select .NET Core inside the Visual C# menu from the left side panel.
Then, select “ASP.NET Core web application“ from available project types. Give a name to the project as StackedChartwithCoreMVCDemo and press OK.
After clicking on the OK button, a new dialog will open to select the project template. You can saw two drop-down menus at the top left of the template window. Then, select “.NET Core” and “ ASP.NET Core 2.1” from these dropdowns. Select “ Web application (Model-View-Controller)” template and press OK to create Asp.Net Core MVC project.
Add a new class to Model folder as “PopulationModel” and implement properties.
namespace StackedChartwithCoreMVCDemo.Models
{
public class PopulationModel
{
public string CityName { get; set; }
public int PopulationYear2020 { get; set; }
public int PopulationYear2010 { get; set; }
public int PopulationYear2000 { get; set; }
public int PopulationYear1990 { get; set; }
}
}
Step 2
Add new class to Model folder for data access and named as “PopulationDataAccessaLayer” and implement the code.
namespace StackedChartwithCoreMVCDemo.Models
{
public class PopulationDataAccessaLayer
{
public static List GetUsStatePopulationList()
{
var list = new List();
list.Add(new PopulationModel { CityName = "Chennai", PopulationYear2020 = 28000, PopulationYear2010 = 15000, PopulationYear2000 = 22000, PopulationYear1990 = 50000 });
list.Add(new PopulationModel { CityName = "Pune", PopulationYear2020 = 30000, PopulationYear2010 = 19000, PopulationYear2000 = 24000, PopulationYear1990 = 39000 });
list.Add(new PopulationModel { CityName = "Kochi", PopulationYear2020 = 35000, PopulationYear2010 = 16000, PopulationYear2000 = 26000, PopulationYear1990 = 41000 });
list.Add(new PopulationModel { CityName = "Kolkata", PopulationYear2020 = 37000, PopulationYear2010 = 14000, PopulationYear2000 = 28000 , PopulationYear1990 = 48000 });
list.Add(new PopulationModel { CityName = "Odisha", PopulationYear2020 = 40000, PopulationYear2010 = 18000, PopulationYear2000 = 30000 , PopulationYear1990 = 54000 });
return list;
}
}
}
Step 3
Add a new controller to Controller folder and name it as “PieChart”.
And create a New Acton Result to display data in view and load Pie chart.
using Microsoft.AspNetCore.Mvc;
using StackedChartwithCoreMVCDemo.Models;
namespace StackedChartwithCoreMVCDemo.Controllers
{
public class PieChartController : Controller
{
// GET: //
public IActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult PopulationChart()
{
var populationList = PopulationDataAccessaLayer.GetCityPopulationList();
return Json(populationList);
}
}
}
Step 4
Add a new folder on Views folder and name it as”PieChart” and add a new view page on “PieChart” folder as”Index.Cshtml”. Add this below code on Index.cshtml page.
@ViewData["Title"] - Pie Chart
google.charts.load('current', {
packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(LoadData);
function LoadData() {
$.ajax({
url: 'PieChart/PopulationChart',
dataType: "json",
type: "GET",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
success: function (data) {
PopulationChart(data);
return false;
}
});
return false;
}
function PopulationChart(data) {
var dataArray = [
['City', '2020 Population', '2010 Population', '2000 Population', '1990 Population']
];
$.each(data, function (i, item) {
dataArray.push([item.cityName, item.populationYear2020, item.populationYear2010, item.populationYear2000, item.populationYear1990]);
});
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Population of Largest Cities of Odisha ',
chartArea: {
width: '50%'
},
colors: ['#b0120a', '#7b1fa2', '#ffab91', '#d95f02'],
hAxis: {
title: 'City',
minValue: 0
},
vAxis: {
title: 'Total Population'
}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
return false;
}
Step 5 - Add a new menu
Edit the Views/Shared/_Layout page and a new menu, as “Pie Chart” and add the below code.
Home
About
Contact
Stacked Chart
Pie Chart
Step 6
Now run the application