我想在chartJs中显示数据库数据,并且数据通过viewData从控制器传输到视图。所有ViewData都有数据且不为空,图表显示静态数据但不显示数据库数据。我的项目是用.NET CORE编写的。请帮助我
C#:
public IActionResult DisplayChartsProvince()
{
if ((User.Claims.FirstOrDefault(c => c.Type == "role").Value == "مدیریت") || (User.Claims.FirstOrDefault(c => c.Type == "role").Value == "معاونت فناوری اطلاعات"))
{
var data = _context.ProvinceLevel.ToList();
var roleTitles = _context.Roles.Select(r => r.RoleTitle).ToList();
List<int> role = new();
List<string> colors = new() { "blue", "red", "yellow", "green", "orange", "#ccc", "olive", "pink" };
for(int i = 0; i < roleTitles.Count; i++)
{
int count = data.Where(r => r.role == roleTitles[i]).ToList().Count;
role.Add(count);
count = 0;
}
ViewData["roleTitles"]= roleTitles;
ViewData["roleCounts"] = role;
ViewData["colors"] =colors;
//////////////////////////////////////////////////////
return View();
}
return View("NotAccessProvince");
}
HTML:
@{
ViewData["Title"] = "گزارش استان - سطح استان";
List<string> RoleTitles = ViewData["roleTitles"] as List<string>;
List<int> RoleCounts = ViewData["roleCounts"] as List<int>;
List<string> Colors = ViewData["colors"] as List<string>;
}
<script src="~/js/chartjs/chart.js"></script>
<div class="btn btn-outline-primary btn-sm my-1 mx-3">گزارش سطح استان</div>
<div class="w-100 d-flex my-2 flex-column px-3">
<div class="card w-100">
<div class="card-header text-primary">
<i class="fa fa-pie-chart"></i>
</div>
<div class="card-body">
<canvas id="d1" class="chart-canvas"></canvas>
</div>
</div>
</div>
@section ChartScripts{
<script>
var d1_Data = [],
d1_labels= [],
d1_colors = [];
@foreach(var item in RoleTitles)
{
<text>d1_Data.push({@item})</text>
}
@foreach(var item in RoleTitles)
{
<text>d1_labels.push({@item})</text>
}
@foreach(var item in Colors)
{
<text>d1_colors.push({@item})</text>
}
new Chart("d1", {
type: "pie",
data: {
labels: d1_labels,
datasets: [{
backgroundColor: d1_colors,
data: d1_Data
}]
},
options: {
title: {
display: true,
}
}
});
</script>
}