Asp.net mvc 将动态数据集添加到chart.js

Asp.net mvc 将动态数据集添加到chart.js,asp.net-mvc,chart.js,Asp.net Mvc,Chart.js,我正在尝试向chart.js图表中动态添加行,其中我不知道有多少数据集 这两天来我的头都被撞到了 我有一个包含年、月和值的列表: public int Month { get; set; } public int Year { get; set; } public int Value { get; set; } 我的HTML只是图表的画布: <div> <canvas id="myChart"> </canvas> </div&

我正在尝试向chart.js图表中动态添加行,其中我不知道有多少数据集 这两天来我的头都被撞到了

我有一个包含年、月和值的列表:

    public int Month { get; set; }
    public int Year { get; set; }
    public int Value { get; set; }
我的HTML只是图表的画布:

<div>
<canvas id="myChart"> </canvas>
</div>
所以问题是,;如何向图表中添加不同的数据集,以便使用类似的内容

@foreach (var year in Model.TurnoverByReservation.OrderBy(x =>x.Month).GroupBy(x => x.Year))
{
foreach (var value in year)
 {
    //Add the value to the dataset, somehow...
 }
}

通过编辑存储在
myChart.config.data
中的数组
datasets
,您可以随时填充数据集数组,即使在调用
new Chart()
函数之后也是如此

假设您从查询中得到类似的结果

var模型={
2015: [20, 12, 32, 8, 25, 14, 20, 12, 32, 8, 25, 14],
2016: [17, 26, 21, 41, 8, 23, 17, 26, 21, 41, 8, 23],
2017: [23, 15, 8, 24, 38, 20, 23, 15, 8, 24, 38, 20]
};
循环到其中,并将所有数据存储在新数据集中:

//对于数据中的每一年。。。
适用于(车型年份){
//您将创建一个新的数据集,其中包含空值和年份作为标签
var newDataset={
标签:年份,
数据:[]
};
//对于该特定年份的每个值。。
对于(车型[年份]中的值){
//填充新创建的数据集
newDataset.data.push(模型[年][值]);
}
//然后将数据集添加到图表中
myChart.config.data.datasets.push(newDataset);
}
//最后,确保更新图表,以便在屏幕上显示结果
myChart.update();
确保您至少使用以下内容启动图表:

var myChart=新图表(ctx、{
键入:“行”,
数据:{
//您需要的标签数量与您拥有的值数量相同
标签:[“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”],
//这将确保您可以从“myChart.config.data.datasets”中获得一些信息`
数据集:[]
}
});

如果您的模型结构不同,您应该仍然能够稍微更改循环以使其工作


您可以在中使用默认数据检查结果。

这是最终有效的解决方案,非常感谢@tektiv的所有帮助

var borderColors = [
    'rgba(255,99,132,1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)',
    'rgba(255, 159, 64, 1)'
];
var backgroundColors = [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)'
];
        var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            label: "#value",
            datasets: []
        },
        options: {
            scales: {
                yAxes: [
                    {
                        ticks: {
                            beginAtZero: true
                        }
                    }
                ]
            }
        }
    });

    @{StringBuilder valueObj = new StringBuilder();}

    var objModel = new Object();

    var myArray = [];
    @foreach (var years in Model.TurnoverByReservation.OrderBy(x => x.Month).GroupBy(x => x.Year))
    {
        foreach (var value in years)
        {
            @:myArray.push("@value.Value");
        }
        @:objModel["@years.Key"] = myArray;
        @:myArray = [];
    }

    var colorInt = 0; //Used to set a variable background and border color

    for (year in objModel) {
        // You create a new dataset with empty values and the year as the label
        var newDataset = {
            label: year,
            data: [],
            backgroundColor: backgroundColors[colorInt],
            borderColor:borderColors[colorInt]
        };
        colorInt += 1;
        // For every value for this specific year ..
        for (value in objModel[year]) {
            // You populate the newly created dataset
            newDataset.data.push(objModel[year][value]);
        }

        // Then you add the dataset to the charts' ones
        myChart.config.data.datasets.push(newDataset);
    }

    // Finally, make sure you update your chart, to get the result on your screen
    myChart.update();

您好,tektiv,谢谢您的回答,它的工作性能:)您能解释一下我如何修改代码,使其与来自mvc模型的数据一起工作吗?像这样:@foreach(Model.TurnoverByReservation.OrderBy(x=>x.Month.GroupBy(x=>x.year)){foreach(var-value in-year){//将值添加到数据集}}@MarcusOhlsson我不习惯于MVC,尤其是.net,尽管我不知道循环导入数据的确切语法。但我相信它和循环中的没有什么不同。我想您需要使用
@foreach(模型中的var year.Overflower…)更改(模型中的年份)
我找到了问题的解决方案:)我用完整的代码更新了问题
var borderColors = [
    'rgba(255,99,132,1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)',
    'rgba(255, 159, 64, 1)'
];
var backgroundColors = [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)'
];
        var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            label: "#value",
            datasets: []
        },
        options: {
            scales: {
                yAxes: [
                    {
                        ticks: {
                            beginAtZero: true
                        }
                    }
                ]
            }
        }
    });

    @{StringBuilder valueObj = new StringBuilder();}

    var objModel = new Object();

    var myArray = [];
    @foreach (var years in Model.TurnoverByReservation.OrderBy(x => x.Month).GroupBy(x => x.Year))
    {
        foreach (var value in years)
        {
            @:myArray.push("@value.Value");
        }
        @:objModel["@years.Key"] = myArray;
        @:myArray = [];
    }

    var colorInt = 0; //Used to set a variable background and border color

    for (year in objModel) {
        // You create a new dataset with empty values and the year as the label
        var newDataset = {
            label: year,
            data: [],
            backgroundColor: backgroundColors[colorInt],
            borderColor:borderColors[colorInt]
        };
        colorInt += 1;
        // For every value for this specific year ..
        for (value in objModel[year]) {
            // You populate the newly created dataset
            newDataset.data.push(objModel[year][value]);
        }

        // Then you add the dataset to the charts' ones
        myChart.config.data.datasets.push(newDataset);
    }

    // Finally, make sure you update your chart, to get the result on your screen
    myChart.update();