- 图表正在显示,但垂直条未显示。数据来自处理程序,但无法分配到变量“data:data. datasets”。请帮助我。*
模型类别
ChartVM.cs*用于定义图表显示的属性 *
public class ChartVM
{
public List<string> Labels{get;set;}
public List<DataSetRow> Datasets{get;set;}
}
public class DataSetRow
{
public List<int> Data{get;set;}
public string BackgroundColor { get;set;}
public string Color { get; set; }
}
图表演示.cs
public JsonResult OnGetBarChart()
{
var vm = new ChartVM();
vm.Labels = new List<string>();
vm.Datasets = new List<DataSetRow>();
var result = context.CountryPopulations.ToList();
vm.Labels = result.Select(x => x.Name).ToList();
var ds1 = new DataSetRow
{
BackgroundColor = "#f2f2f2",
Color = "#24248f",
Data = result.Select(x => x.Male).ToList()
};
var ds2 = new DataSetRow
{
BackgroundColor = "#f2f2f2",
Color = "#ff0080",
Data = result.Select(x => x.Female).ToList()
};
vm.Datasets.Add(ds1);
vm.Datasets.Add(ds2);
return new JsonResult(vm);
}
图表演示.cshtml
HTML代码
<div>
<canvas id="myChart" style="max-height:400px; max-width:500px"></canvas>
</div>
Java脚本
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/chart.min.js" asp-append-version="true"></script>
<script type="text/javascript">
$(document).ready(function () {
BarChart();
});
function BarChart() {
var XaxisTitle = 'Colour Bar';
var Yaxistitle = 'Rupees';
var legendTitle = 'Months';
const ctx = document.getElementById('myChart');
debugger;
$.ajax({
type:'GET',
url:'?handler=BarChart',
data:{},
success:function(data){
new Chart(ctx, {
type: 'bar',
data: {
labels:data.labels,
datasets: [{
label: legendTitle,
data:data.datasets,
borderWidth: 1,
}]
},
options: {
scales: {
x: {
display: true,
beginAtZero: true,
title: {
display: true,
text: XaxisTitle,
color: '#911',
font: {
family: 'Comic Sans MS',
size: 20,
weight: 'bold',
lineHeight: 1.2,
},
padding: { top: 20, left: 0, right: 0, bottom: 0 }
}
},
y: {
display: true,
title: {
display: true,
text: Yaxistitle,
color: '#191',
font: {
family: 'Times',
size: 20,
style: 'normal',
lineHeight: 1.2
},
padding: { top: 30, left: 0, right: 0, bottom: 0 }
}
}
}
}
});
},
error:function(){
alert('Something went wrong!!');
}
});
}
</script>
查看输出图像垂直条未显示
1条答案
按热度按时间pepwfjgg1#
但它不能赋值给变量“data:data.datasets”
错误就在这里:
chartjs中的单个数据集是具有数据点和选项的复杂对象。
因此,在提供的示例中,您尝试将数据集串传递给data points属性(基元整数值数组)。
快速修复:
更改颜色并从here中删除数据。
显示排名前10位的国家: