首页 > 解决方案 > ASP.NET Core Razor 页面 - 获取要在 Chart.js 图表上显示的列表数据

问题描述

我有一个已填充的列表 (lstObjects),并试图让该数据显示在我的 Chartist.js 图表上。当我将 lstObjects 悬停在调试模式下时,我可以看到我的列表计数和对象类型。

在我的<script>标签中,我目前有:

    var chartOptions = {
    showLines: true,
    responsive: true,
    maintainAspectRatio: false,
    legend: {
        display: false
    },
        tooltips: {
        displayColors: false
    },
    scales: {

        xAxes: [{
            display: true,
            ticks: {
                fontColor: 'black',
                padding: 20

            },
            gridLines: {
                borderDash: [1, 5],
                tickMarkLength: 0,
                zeroLineBorderDash: [1, 5],
                drawBorder: false,
                padding: 5
            }
        }],
        yAxes: [{
            display: true,
            ticks: {
                fontColor: 'black',
                padding: 20
            },
            gridLines: {
                color: 'rgba(85, 85, 85, 0.5)',
                borderDash: [1, 5],
                tickMarkLength: 0,
                zeroLineBorderDash: [1, 5],
                drawBorder: false,
                padding: 5
            }
        }]
    }
};

// Total Transactions Chart
var achChart = new Chart(document.getElementById('myChart').getContext('2d'), {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'],
        datasets: [{
            label: '',
            lineTension: 0,
            fill: false,
            backgroundColor: 'rgb(25, 255, 102)',
            borderColor: 'rgba(25, 255, 102, 0.4)',
            borderWidth: 5,
            data: [0, 600, 200, 450, 800, 900, 550, 700, 800, 600]

        }]
    },
    options: chartOptions,

});

我希望数据数据做这样的事情:

 labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
 data: [100, 120, 180, 200, 300, 155, 220, 430, 275, 350, 120, 450]

我知道我需要将列表项转换为字符串并尝试加入我的 SubmitDate 但我无法让它工作。

var submitDate = string.Join("','", @Model.lstObjects.Select(x => x.RecordMonth).ToList());

有人对我如何完成这项工作有任何建议吗?

标签: javascriptc#chart.jsrazor-pagesasp.net-core-3.1

解决方案


我能够使用逗号上的@Html.Rawand来完成这项工作。String.Join我还添加了刻度来围绕 Month 字符串,例如'Jan'.

下面是我所做的一个示例。

data: {
      labels: [@Html.Raw("'" + String.Join("','", (Model.lstObjects.Select(x => x.RecordMonth).ToList())) + "'")],

推荐阅读