简体   繁体   中英

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. 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; and I will leave it to you to implement access to your SQL Database. But hopefully this solution can help you too!

Try using the following in the .ASPX file:

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

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;
  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. 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 serializer = new JavaScriptSerializer(); weeklyData = serializer.Serialize(data);

  2. Assign weeklyData variable in your chart initialization code like: data: <%= weeklyData %>, enter code here

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. Then, you can use jquery get method to get data and then initialize chart

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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