简体   繁体   English

使用C#从SQL数据库动态更改图表数据

[英]Changing chart data dynamically with C# from SQL database

This is my chart code. 这是我的图表代码。

<!-- Graphs -->
<script src="../Scripts/Chart.min.js"></script>
<script>
  var ctx = document.getElementById("myChart");
  var myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
      datasets: [{
        data: [1, 6, 2, 5, 9, 5, 6],
        label: "Issues Resolved",
        lineTension: 0,
        backgroundColor: 'transparent',
        borderColor: '#007bff',
        borderWidth: 4,
        pointBackgroundColor: '#007bff'
      }, {
                data: [8, 5, 8, 6, 0, 2, 2],
                label: "Issues Raised",
                lineTension: 0,
                backgroundColor: 'transparent',
                borderColor: '#ff8400',
                borderWidth: 4,
                pointBackgroundColor: '#ff8400'
          }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: false
          }
        }]
      },
        legend: {
            display: true
        },
        title: {
                  display: true,
                  text: 'Issues Raised VS Issues Resolved'
                }
    }
    });
</script>

This graph, though working fine, is static. 该图虽然工作正常,但是静态的。 What I want to ask is whether I can dynamically change the data (of which I'll always have 7 values, for each day of the week) in my datasets (of which I'll always have 2 values, for issues raised and issues resolved) from my .aspx.cs (which will get this data from my SQL Database) at runtime. 我想问的是,对于引发的问题和问题,我是否可以动态更改data datasets (一周中的每一天总是有7个值)在运行时从我的.aspx.cs(将从我的SQL数据库获取此数据)中解析。 And if so, how? 如果是这样,怎么办?

Thank you for your help. 谢谢您的帮助。

I had a similar issue and found this solution. 我遇到了类似的问题,并找到了解决方案。 This solution requires you to use using System.Web.Services; 该解决方案要求您using System.Web.Services;来使用using System.Web.Services; and I will leave it to you to implement access to your SQL Database. 我将留给您以实现对SQL数据库的访问。 But hopefully this solution can help you too! 但是希望该解决方案也能为您提供帮助!

Try using the following in the .ASPX file: 尝试在.ASPX文件中使用以下内容:

<!-- Graphs -->
<script src="../Scripts/Chart.min.js"></script>
<script>
    $(function () {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: 'BackendFileName.aspx/GetChartData', // change to your .aspx filename
            data: '{}',
            success: function (response) {
                drawChart(response.d);
            },

            error: function () {
                console.error("Error loading data! Please try again.");
            }
        });
    })

    function drawChart(dataValues) {
        var issuesResolved = [];
        var issuesRaised = [];
        for (var i = 0; i < dataValues.length; i++) {
            issuesResolved[i] = dataValues[i].issuesResolved;
            issuesRaised[i] = dataValues[i].issuesRaised;
        }
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
                datasets: [{
                    data: issuesResolved,
                    label: "Issues Resolved",
                    lineTension: 0,
                    backgroundColor: 'transparent',
                    borderColor: '#007bff',
                    borderWidth: 4,
                    pointBackgroundColor: '#007bff'
                }, {
                    data: issuesRaised,
                    label: "Issues Raised",
                    lineTension: 0,
                    backgroundColor: 'transparent',
                    borderColor: '#ff8400',
                    borderWidth: 4,
                    pointBackgroundColor: '#ff8400'
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: false
                        }
                    }]
                },
                legend: {
                    display: true
                },
                title: {
                    display: true,
                    text: 'Issues Raised VS Issues Resolved'
                }
            }
        });
    }
</script>

Then add the following methods within backend file: 然后在后端文件中添加以下方法:

// Arbitrary class to hold required data from SQL Database
public class ChartDetails
{
    public string IssuesResolved { get; set; }

    public string IssuesRaised { get; set; }

    public ChartDetails()
    {
    }
}

// Method that will be called by JQuery script
[WebMethod]
public static List<ChartDetails> GetChartData()
{
    List<ChartDetails> dataList = new List<ChartDetails>();

    // Access SQL Database Data
    // Assign SQL Data to List<ChartDetails> dataList

    return dataList;
}

You most certainly can. 您当然可以。 Take a look at the documentation here , you just need to implement the AJAX polling to see if the source dataset has changed. 这里查看文档,您只需要实现AJAX轮询即可查看源数据集是否已更改。

I believe what you can do is: 我相信您可以做的是:

  1. Create a class level string variable in your code behind for holding the serialized array like protected string weeklyData; 在您的代码后面创建一个类级别的字符串变量,用于保存序列化数组,例如protected string weeklyData;
  2. In Page_Load eventhandler, fetch the data from SQL database and populate an array of numbers int or decimal or floats depending upon your stored data. 在Page_Load事件处理程序中,从SQL数据库中获取数据,并根据存储的数据填充数字数组int或小数或浮点数。 Lets say you end up with an array containing data 假设您最终得到一个包含数据的数组

int[] data = [8, 5, 8, 6, 0, 2, 2];

  1. Use the JavaScriptSerializer class to serialize it into a string and assign to weeklyData class variable like this: 使用JavaScriptSerializer类将其序列化为字符串,然后将其分配给weeklyData类变量,如下所示:

    JavaScriptSerializer serializer = new JavaScriptSerializer(); weeklyData = serializer.Serialize(data);

  2. Assign weeklyData variable in your chart initialization code like: data: <%= weeklyData %>, enter code here 在图表初始化代码中分配weeklyData变量,例如: data: <%= weeklyData %>,在此处输入代码

Another better option will be to write a WEB API service which will expose an endpoint for fetching the weekly data in json array format. 另一个更好的选择是编写一个WEB API服务,该服务将公开一个端点,以json数组格式获取每周数据。 Then, you can use jquery get method to get data and then initialize chart 然后,您可以使用jquery的get方法获取数据,然后初始化图表

$.get('{enpointurl}', function(weeklyData) {
  //Write chart initialization code here and pass weekly data to chart data option
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM