将ViewBag数据加载到chart.js多图表中

时间:2019-01-11 10:48:19

标签: javascript c# jquery chart.js viewbag

我正在尝试从两个Viewbag加载数据,一个包含一个条形图的数据,另一个包含一个线形图的数据,这两个都包含来自数据库查询的数据,如下所示:

var outcomeData = "@Html.Raw(@ViewBag.ChartOutput)";
var avgDaysUseData = "@Html.Raw(@ViewBag.AvgDaysUseChartOutput)";
var outcomeArray = outcomeData.replace(/\[/g, "").replace(/\]/g, "").replace(/\'/g, "").split(',');
var avgDaysUseArray = avgDaysUseData.replace(/\[/g, "").replace(/\]/g, "").replace(/\'/g, "").split(',');
var reportingPeriods = [];
var outcomeNames = [];
var outcomeValues = [];
var avgDaysUseValues = [];

    $.each(avgDaysUseArray,
        function (index, value) {
            if (Number.isNaN(value) === false) {
                value = parseFloat(value);
                avgDaysUseValues.push(value);
            }
        });

    $.each(outcomeArray,
        function (index, value) {
            var reportingPeriod = new RegExp('\\d{4}(\/)\\d{2}');
            var isReportingPeriod = reportingPeriod.test(value);
            if (isReportingPeriod) {
                reportingPeriods.push(value);
            }
            else {
                var outcomeName = new RegExp('[a-zA-Z]');
                var isOutcomeName = outcomeName.test(value);
                if (isOutcomeName) {
                    if (value !== "Outcomes") {
                        outcomeNames.push(value);
                    }
                } else {
                    value = parseInt(value);
                    outcomeValues.push(value);
                }
            }
        });

    var ctx = document.getElementById('chart');

    var outcomeChart = new Chart(ctx,
        {
            type: 'bar',
            data: {
                labels: reportingPeriods,
                datasets: [
                    {
                        type: 'line', fill: false, lineTension: 0,
                        label: 'Average days of use at start',
                        data: [avgDaysUseValues[4], avgDaysUseValues[7], avgDaysUseValues[10]],
                        yAxisId: 'y-axis-1',
                        borderColor: 'Black',
                        backgroundColor: 'Black',
                        borderWidth: 2
                    },
                    {
                        type: 'line', fill: false, lineTension: 0,
                        label: 'Average days of use at review',
                        data: [avgDaysUseValues[5], avgDaysUseValues[8], avgDaysUseValues[11]],
                        yAxisId: 'y-axis-1',
                        borderColor: 'Blue',
                        backgroundColor: 'Blue',
                        borderWidth: 2
                    },
                    {
                        type: 'bar',
                        label: outcomeNames[0],
                        data: [outcomeValues[0], outcomeValues[4], outcomeValues[8]],
                        yAxisID: 'y-axis-2',
                        borderColor: '#FF9900',
                        backgroundColor: '#FF9900',
                        borderWidth: 2
                    },
                    {
                        type: 'bar',
                        label: outcomeNames[1],
                        data: [outcomeValues[1], outcomeValues[5], outcomeValues[9]],
                        yAxisID: 'y-axis-2',
                        borderColor: '#FF6400',
                        backgroundColor: '#FF6400',
                        borderWidth: 2
                    },
                    {
                        type: 'bar',
                        label: outcomeNames[2],
                        data: [outcomeValues[2], outcomeValues[6], outcomeValues[10]],
                        yAxisID: 'y-axis-2',
                        borderColor: '#FF0000',
                        backgroundColor: '#FF0000',
                        borderWidth: 2
                    },
                    {
                        type: 'bar',
                        label: outcomeNames[3],
                        data: [outcomeValues[3], outcomeValues[7], outcomeValues[11]],
                        yAxisID: 'y-axis-2',
                        borderColor: '#9A0033',
                        backgroundColor: '#9A0033',
                        borderWidth: 2
                    }
                ]
            },
            options: { scales: {
                xAxes: [
                    {
                        gridLines: {
                            display: false
                        },
                        scaleLabel: { display: true, labelString: 'Reporting Period', fontStyle: 'italic' },
                        position: 'bottom',
                        ticks: { fontStyle: 'italic' },
                        barPercentage: 0.95,
                        categoryPercentage: 0.15
                    }
                ],
                yAxes: [
                    {
                        scaleLabel: { display: true, labelString: 'Average no. of days', fontStyle: 'italic' },
                        position: 'right', id: 'y-axis-1', type: 'linear',
                        ticks: { min: 0, beginAtZero: true, max: 28 },
                        gridLines: {display: true}
                    },
                    {
                        scaleLabel: { display: true, labelString: 'No. of clients', fontStyle: 'italic' },
                        position: 'left', id: 'y-axis-2',type: 'linear',
                        gridLines: { display: false }
                    }]
            },
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    position: 'right',
                    display: true,
                    onClick: null,
                    labels: {
                        fontColor: '#000000'
                    }
                }
            }
        });

    outcomeChart.aspectRatio = 0;


    $('#chart').bind('contextmenu',
        function(e) {
            return false;
        });

我在Codepen中提供了一个工作示例,以显示正在生成的内容以及我希望它如何显示,我在Codepen中提供的示例数据是ViewBag中包含的内容:

https://codepen.io/gameloregeek/pen/GPXBdp

我如何使用两个Viewbag中的数据来创建多图表,如Codepen中的示例?


作为示例,以下是每个视图包中的数据格式:

条形图数据

var outcomeData = "['Outcomes','Abstinent','Improved','Unchanged','Deteriorated'],['2015/16',18036,11414,14430,1880],['2016/17',17642,11688,14010,1738],['2017/18',17282,10796,13542,1686]";

折线图数据

var avgDaysUseData = "['year','AvgDaysUseAtStart','AvgDaysUseAtReview'],['2015/16',21.6,8.3],['2016/17',22.2,8.5],['2017/18',22.1,8.6]";

已经修改了我的代码,但是我不能使用Json编码数据,因为它包含包含正斜杠的值,正斜杠被解释为转义值:

<script type="text/javascript">
    var outcomeData = "@Html.Raw(Json.Encode(@ViewBag.ChartOutput))";
    var avgDaysUseData = "@Html.Raw(Json.Encode(@ViewBag.AvgDaysUseChartOutput))";
    outcomeArray = [];

    for (var i = 0; i < outcomeData.length; i++) {
        outcomeArray[i] = outcomeData[i];
    }
    var ctx = document.getElementById('chart');

    var outcomeChart = new Chart(ctx,
        {
            type: 'bar',
            data: outcomeArray,
            options: { scales: {
                xAxes: [
                    {
                        gridLines: {
                            display: false
                        },
                        scaleLabel: { display: true, labelString: 'Reporting Period', fontStyle: 'italic' },
                        position: 'bottom',
                        ticks: { fontStyle: 'italic' },
                        barPercentage: 0.95,
                        categoryPercentage: 0.15
                    }
                ],
                yAxes: [
                    {
                        scaleLabel: { display: true, labelString: 'Average no. of days', fontStyle: 'italic' },
                        position: 'right', id: 'y-axis-1', type: 'linear',
                        ticks: { min: 0, beginAtZero: true, max: 28 },
                        gridLines: {display: true}
                    },
                    {
                        scaleLabel: { display: true, labelString: '@Model.XAxis', fontStyle: 'italic' },
                        position: 'left', id: 'y-axis-2',type: 'linear',
                        gridLines: { display: false }
                    }]
            },
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    position: 'right',
                    display: true,
                    onClick: null,
                    labels: {
                        fontColor: '#000000'
                    }
                }
            }
        });

    outcomeChart.aspectRatio = 0;


    $('#chart').bind('contextmenu',
        function(e) {
            return false;
        });
</script>

编码后的数据如下:

 var outcomeData = ""[\u0027Outcomes\u0027,\u0027Abstinent\u0027,\u0027Improved\u0027,\u0027Unchanged\u0027,\u0027Deteriorated\u0027],[\u00272015/16\u0027,18036,11414,14430,1880],[\u00272016/17\u0027,17642,11688,14010,1738],[\u00272017/18\u0027,17282,10796,13542,1686]"";

,控制台中的错误如下 SyntaxError:无效的转义序列

1 个答案:

答案 0 :(得分:1)

如果它是ViewBag中的C#数组:

var outcomeData = @Html.Raw(Json.Encode(@ViewBag.ChartOutput));

使用Json.EncodeHtml.Raw

使用完整链接:


如果它在Viewbag中是字符串: 您可以像这样在JS中使用ViewBag中的值:

var outcomeData = '@ViewBag.ChartOutput';

那么您就不需要Html.Raw