locked
using Chart.js to dynamically bind data RRS feed

  • Question

  • User-153404742 posted

    Hi,

    We're actually not using MVC, which would've made this easier as all the examples I come across are using MVC...but using web forms, If I have a lINQ object that has

    select new { key = grp.Key, cnt = grp.Count() }) and I want to graph a bar graph using canvas.js bar graph, how can I write javascript function to graph the Key on x-axis and count on y-axis?

    label: this should be the value from grp.Key
    data: grp.Count value from the object

    Thanks for your help.

    Friday, September 28, 2018 6:01 PM

Answers

  • User475983607 posted

    Chart.js is a client side API.  MVC examples should work fine in Web Forms.  The only difference is Web Forms used code blocks <% %> and MVC uses Razor syntax @.  If you are using AJAX to populate the chart.js API then MVC uses Controller Actions and Web Forms uses Web Methods.

    It would help if you posted the code you're working on and explain the issues you are facing.

    I went ahead and build an example based on the chart.js bar code documentation.

    http://www.chartjs.org/docs/latest/

    The main idea is the data elements are created on the server and stored in properties .  The properties are serialized to JSON in the markup using NewtonSoft (NuGet).

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChartJsDemo.aspx.cs" Inherits="WebFormsApp.ChartJsDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.3.1.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
    
    </head>
    <body>
        <div id="container" style="width:50%">
            <canvas id="canvas" width="400" height="400"></canvas>
        </div>
        
    
        <script>
        var ctx = document.getElementById("canvas").getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: <%=Newtonsoft.Json.JsonConvert.SerializeObject(Labels)%>,
                datasets: [{
                    label: '<%=Legend%>',
                    data: <%=Newtonsoft.Json.JsonConvert.SerializeObject(Data)%>,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
                }
            }
        });
        </script>
    </body>
    </html>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsApp
    {
        public partial class ChartJsDemo : System.Web.UI.Page
        {
            public string[] Labels { get; set; }
            public string Legend { get; set; }
            public int[] Data { get; set; }
            protected void Page_Load(object sender, EventArgs e)
            {
                Labels = new string[] { "Red", "Blue", "Yellow", "Green", "Purple", "Orange" };
                Legend = "# of Votes";
                Data = new int[] { 12, 19, 3, 5, 2, 3 };
    
                
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 28, 2018 6:46 PM

All replies

  • User475983607 posted

    Chart.js is a client side API.  MVC examples should work fine in Web Forms.  The only difference is Web Forms used code blocks <% %> and MVC uses Razor syntax @.  If you are using AJAX to populate the chart.js API then MVC uses Controller Actions and Web Forms uses Web Methods.

    It would help if you posted the code you're working on and explain the issues you are facing.

    I went ahead and build an example based on the chart.js bar code documentation.

    http://www.chartjs.org/docs/latest/

    The main idea is the data elements are created on the server and stored in properties .  The properties are serialized to JSON in the markup using NewtonSoft (NuGet).

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChartJsDemo.aspx.cs" Inherits="WebFormsApp.ChartJsDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.3.1.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
    
    </head>
    <body>
        <div id="container" style="width:50%">
            <canvas id="canvas" width="400" height="400"></canvas>
        </div>
        
    
        <script>
        var ctx = document.getElementById("canvas").getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: <%=Newtonsoft.Json.JsonConvert.SerializeObject(Labels)%>,
                datasets: [{
                    label: '<%=Legend%>',
                    data: <%=Newtonsoft.Json.JsonConvert.SerializeObject(Data)%>,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
                }
            }
        });
        </script>
    </body>
    </html>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsApp
    {
        public partial class ChartJsDemo : System.Web.UI.Page
        {
            public string[] Labels { get; set; }
            public string Legend { get; set; }
            public int[] Data { get; set; }
            protected void Page_Load(object sender, EventArgs e)
            {
                Labels = new string[] { "Red", "Blue", "Yellow", "Green", "Purple", "Orange" };
                Legend = "# of Votes";
                Data = new int[] { 12, 19, 3, 5, 2, 3 };
    
                
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 28, 2018 6:46 PM
  • User-153404742 posted

    Thank You....I was working with .net chart and couldn't display the x-axis values that were missing.  I.e. if I have 1,2,5 for x-axis values it graphs just those but I wanted them to show the 1,2,3,4,5 on x-axis and set the default Y-value for 3 and 4 that are not in the dataset to 0 but they still show on the number line.  It's the same issue with chart.js....not sure why it doesn't work.  Tried setting the xAxes Intervalt to 1, stepsize to 1 and still nothing.  Is there an easy way to show the missing numbers on x-axes scale with chart.js?  Thx.

    Friday, September 28, 2018 8:21 PM
  • User475983607 posted

    Thank You....I was working with .net chart and couldn't display the x-axis values that were missing.  I.e. if I have 1,2,5 for x-axis values it graphs just those but I wanted them to show the 1,2,3,4,5 on x-axis and set the default Y-value for 3 and 4 that are not in the dataset to 0 but they still show on the number line.  It's the same issue with chart.js....not sure why it doesn't work.  Tried setting the xAxes Intervalt to 1, stepsize to 1 and still nothing.  Is there an easy way to show the missing numbers on x-axes scale with chart.js?  Thx.

    It seems like you are asking a new question but I have no idea what problem you are trying to solve.  In the demo the x-axis is the name of an bar.  The y-axis has the value.  Perhaps you need a different kind of chart.  

    Friday, September 28, 2018 8:40 PM
  • User-153404742 posted

    Hi,

    The solution you provided worked for a sample graph....it's giving me the following error and it may be because of jQuery library but not sure how to fix.

    Uncaught ReferenceError: Newtonsoft is not defined
    at HTMLDocument.<anonymous> (https://localhost:/Scripts/bootstrap/bargraph.js:3:17)
    at j (https://localhost:44310/Scripts/bootstrap/jquery-3.2.1.min.js:2:29999)
    at k (https://localhost:44310/Scripts/bootstrap/jquery-3.2.1.min.js:2:30313) undefined
    r.Deferred.exceptionHook @ jquery-3.2.1.min.js:2

    the bargraph.js has the following that's throwing the error....

    $(document).ready(function () {
        var rawData = {
            Labels: Newtonsoft.Json.JsonConvert.SerializeObject(Labels),
            Data: Newtonsoft.Json.JsonConvert.SerializeObject(Data),
        }
     
        var addData= adding(rawData);
    It works with sample data when I use the following:
    $(document).ready(function () {
        var rawData = {
            Labels: ["1", "5", "10"],
            Data: [3,5,9],
        }
     
        var addData= adding(rawData);
    Any ideas why I can't use the Newtonsoft.Json.JsonConvert.SerializeObject(Labels), to pass in the list of strings as labels and list of integers as Data from c# code behind?

    Monday, October 1, 2018 7:07 PM
  • User475983607 posted

    Hi,

    The solution you provided worked for a sample graph....it's giving me the following error and it may be because of jQuery library but not sure how to fix.

    Uncaught ReferenceError: Newtonsoft is not defined
    at HTMLDocument.<anonymous> (https://localhost:/Scripts/bootstrap/bargraph.js:3:17)
    at j (https://localhost:44310/Scripts/bootstrap/jquery-3.2.1.min.js:2:29999)
    at k (https://localhost:44310/Scripts/bootstrap/jquery-3.2.1.min.js:2:30313) undefined
    r.Deferred.exceptionHook @ jquery-3.2.1.min.js:2

    the bargraph.js has the following that's throwing the error....

    <div>$(document).ready(function () {</div> <div>    var rawData = {</div> <div>        Labels: Newtonsoft.Json.JsonConvert.SerializeObject(Labels),</div> <div>        Data: Newtonsoft.Json.JsonConvert.SerializeObject(Data),</div> <div>    }</div> <div> </div> <div>    var addData= adding(rawData);</div> <div></div> <div>It works with sample data when I use the following:</div> <div></div> <div> <div>$(document).ready(function () {</div> <div>    var rawData = {</div> <div>        Labels: ["1", "5", "10"],</div> <div>        Data: [3,5,9],</div> <div>    }</div> <div> </div> <div>     var addData= adding(rawData);</div> <div></div> <div></div> <div>Any ideas why I can't use the Newtonsoft.Json.JsonConvert.SerializeObject(Labels), to pass in the list of strings as labels and list of integers as Data from c# code behind?</div> </div>

    Add the NewtonSoft NuGet package as suggested in the post.

    https://www.nuget.org/packages/Newtonsoft.Json/

    Newtonsoft is the standard JSON serializer in the newer ASP Core.  It works just as well in ASP.NET.

    Monday, October 1, 2018 7:44 PM