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

时间:2018-06-20 16:54:36

标签: javascript c# asp.net chart.js

这是我的图表代码。

<!-- 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>

该图虽然工作正常,但是静态的。我想问的是,我data(我将始终拥有)中的datasets(在一周中的每一天中始终具有7个值)是否可以动态更改。 2个值,用于在运行时从我的.aspx.cs(将从我的SQL数据库获取此数据)中提出的问题和已解决的问题。如果可以,怎么办?

谢谢您的帮助。

4 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,并找到了解决方案。此解决方案要求您使用using System.Web.Services;,我将留给您以实现对SQL数据库的访问。但希望该解决方案也能为您提供帮助!

尝试在.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>

然后在后端文件中添加以下方法:

// 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;
}

答案 1 :(得分:0)

您当然可以。看一下文档here,您只需要实现AJAX轮询即可查看源数据集是否已更改。

答案 2 :(得分:0)

我相信您可以做的是:

  1. 在后面的代码中创建一个类级别的字符串变量,用于保存序列化数组,例如  protected string weeklyData;
  2. 在Page_Load事件处理程序中,从SQL数据库中获取数据并根据存储的数据填充一个数字数组int或小数或浮点数。可以说您最终得到一个包含数据的数组

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

  1. 使用JavaScriptSerializer类将其序列化为字符串,然后将其分配给weeklyData类变量,如下所示:

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

  2. 在图表初始化代码中分配weeklyData变量,例如:  data: <%= weeklyData %>, 在此处输入代码

另一个更好的选择是编写一个WEB API服务,该服务将公开一个端点,以json数组格式获取每周数据。然后,可以使用jquery的get方法获取数据,然后初始化图表

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

答案 3 :(得分:0)

添加隐藏字段:

<asp:HiddenField ID="hdnLabels" runat="server" Value="" />
<asp:HiddenField ID="hdnData" runat="server" Value="" />

在图表脚本中添加:

labels: [<%= hdnLabels.Value %>],
datasets: [
    {
        data: [ <%= hdnData.Value %>],
        ... other options here,

    }
]

在后面的代码中:

 public void ShowChartData()
    string _data = "";
    string _labels = "";

    ......Loop your SqlDataReader
    ....
    ....
    while (dr.Read())
    {
        _labels = _data + dr["DayOfWeek"].ToString() + @",";
        _data = _data + dr["DayOfWeekValue"].ToString() + @",";
    }

    _labels = _label.Remove(_label.Length - 1);
    _data = _data.Remove(_data.Length - 1);
    hdnLabels.Value = _labels;
    hdnData.Value = _data;
}

希望这对您有帮助...