locked
c# chart.js webform help RRS feed

  • Question

  • User-840896699 posted

    Hi

    my  default.aspx.cs code :

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="ChartDene._default" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>

    <script src="https://cdnjs.com/libraries/Chart.js"></script>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

    </head>
    <body>
    <form id="form1" runat="server">
    <canvas id="myChart" width="400" height="400"></canvas>
    </form>
    </body>
    </html>

    and

    defaul.aspx is

    protected void Page_Load(object sender, EventArgs e)
    {
    string chart = "";
    chart += "<script>";
    chart += "var ctx = document.getElementById('myChart').getContext('2d');";
    chart += "var myChart = new Chart(ctx, {";
    chart += " type: 'bar',";
    chart += " data:";
    chart += " {";
    chart += " labels: ['Red', 'Blue'],";
    chart += " datasets: [{";
    chart += " data: [110, 2000]";
    chart += " }]";
    chart += " },";
    chart += " });";
    chart += "</script>";
    }

    Chart is not displaying

    please help me,

    Monday, July 15, 2019 5:40 PM

All replies

  • User475983607 posted

    See the following.

    https://forums.asp.net/p/2129509/6169081.aspx

    Monday, July 15, 2019 5:44 PM
  • User288213138 posted

    Hi infotba,

    When you put the script into code behind, you should use RegisterStartupScript method to Registers the startup script with the Page object.

    More information about RegisterStartupScript you can reference this link: https://forums.asp.net/t/2157780.aspx

    Note: The code I tested is my own chart.js

    The code:

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <canvas id="myChart" width="400" height="400"></canvas>
    
    string chart = "";
                chart += "<script>";
                chart += "var ctx = document.getElementById('myChart').getContext('2d');";
                chart += "var myChart = new Chart(ctx, {";
                chart += " type: 'bar',";
                chart += " data:";
                chart += " {";
                chart += " labels: ['Red', 'Blue'],";
                chart += " datasets: [{";
                chart += " data: [110, 2000]";
                chart += " }]";
                chart += " },";
                chart += " });";
                chart += "</script>";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", chart, false);
    

    The result:

    Best regards,

    Sam

    Tuesday, July 16, 2019 3:26 AM
  • User-2054057000 posted

    You are just starting with Chart.js. This is covered really well in this thread: 

    help : populate chart

    Tuesday, July 16, 2019 5:45 AM