从数据表/ SQL结果集中填充chart.js

时间:2018-04-09 17:52:04

标签: c# asp.net chart.js

基于SQL结果集,我打算填充一个数据表,用作图表的数据源(使用chart.js)。 关于如何使用C#/ ASP.NET进行此工作的任何想法,因为我没有找到任何工作示例? 非常感谢

1 个答案:

答案 0 :(得分:0)

我创建了以下从后端调用的Javascript方法

function FillBarChart(names, values, canvasId, graphTitle, labels) {
        var color = Chart.helpers.color;
        var colors = '#' + Math.floor(Math.random() * 16777215).toString(16);
        var collors = 'hsla(' + (Math.floor(Math.random() * 360) + ', 70%, 70%, 1)');
        var chartData = {
            labels: names.split(','),
            datasets: [
                {
                    label: labels,
                    backgroundColor: collors,
                    borderColor: color("#0061ff"),
                    borderWidth: 1,
                    data: values.split(',')
                }
            ]
        };
        var ctx = document.getElementById(canvasId).getContext('2d');
        window.barChart = new Chart(ctx, {
            type: 'bar',
            data: chartData,
            options: {
                responsive: true,
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: graphTitle
                }
            }
        });
    }

触发此操作的C#行如下:

StringBuilder javascriptCommands = new StringBuilder();

            HtmlGenericControl canvas = new HtmlGenericControl();
            canvas.TagName = "canvas";
            canvas.Attributes["Height"] = CanvasHeight;
            canvas.ClientIDMode = ClientIDMode.Static;
            canvas.ID = "canvasSales";
            string graphNames = "Previous Year,Current Year";
            string graphValues = MainSession.salesPY + "," + MainSession.salesCY;
            charts.Controls.Add(canvas);
            javascriptCommands.Append("FillBarChart(`" + graphNames + "`,`" + graphValues + "`,`" + canvas.ID + "`,`" + "Grand Total Sales" + "`,`" + "Total Sales Graph" + "`);");

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mykey", javascriptCommands.ToString(), true);

MainSession.salesPY和MainSession.salesCY是所需的值,在我的情况下从SQL引入并连接为字符串,用逗号分隔。