You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 Razor Pages中Chart.js柱状图无竖条问题求助

.NET 6 Razor Pages 中 Chart.js 柱状图条形不显示问题

问题描述

在.NET 6 Razor Pages中使用Chart.js实现柱状图时,图表框架正常显示,但垂直条形未渲染。已通过后端OnGetBarChart处理器获取到数据,但无法正确赋值给Chart配置的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; }
}

后端处理器(ChartDemo.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);

 }

前端页面(ChartDemo.cshtml)

HTML部分

<div>
    <canvas id="myChart" style="max-height:400px; max-width:500px"></canvas>
</div>

原JavaScript代码(存在问题)

<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');
        $.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>

问题原因及修复方案

核心问题

前端代码错误地将后端返回的data.datasets(完整数据集数组)直接赋值给单个dataset的data字段。Chart.js要求每个dataset的data是对应标签的数值数组,而非数据集对象数组,导致数据无法被正确解析渲染。

修复后的JavaScript代码

<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 = '国家';
        var Yaxistitle = '人口数量';
        const ctx = document.getElementById('myChart');
        $.ajax({
            type:'GET',
            url:'?handler=BarChart',
            data:{},
            success:function(data){
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: data.labels,
                        // 分别映射后端返回的两个数据集
                        datasets: [
                            {
                                label: '男性人口',
                                data: data.datasets[0].data,
                                backgroundColor: data.datasets[0].BackgroundColor,
                                borderColor: data.datasets[0].Color,
                                borderWidth: 1                                                        
                            },
                            {
                                label: '女性人口',
                                data: data.datasets[1].data,
                                backgroundColor: data.datasets[1].BackgroundColor,
                                borderColor: data.datasets[1].Color,
                                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,
                                beginAtZero: true, // 确保Y轴从0开始,避免数据范围导致条形不可见
                                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('加载数据失败!');
            }
        });
    }
</script>

额外优化点

  1. 修正了标题文本,使其与实际业务数据(国家人口)匹配
  2. 为Y轴添加beginAtZero: true配置,确保数值从0起点显示
  3. 正确映射后端返回的BackgroundColor和Color字段到Chart.js的对应配置项

内容的提问来源于stack exchange,提问作者MD SAQUIB RAZA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:16:07