locked
Passing JavaScript Object from Code Behind to JavaScript code in aspx page RRS feed

  • Question

  • User567064909 posted

    Hello everyone..

    I am trying to pass a JavaScript Object with multiple values of bootstrap chart data from C# Code Behind to JavaScript code in aspx page .. I have write the following code but no chart appear and it gives me a JavaScript error.

    protected void Page_Load(object sender, EventArgs e)
            {
                    // Chart
    
                    LineChartData.Value = GetLineChartData(); 
                   
                   // LineChartData is a hidden input control at aspx page
                }
            }
    // Method to create javascript object of chart data
    
    string GetLineChartData()
            {
                string LineChartData = "{labels: ['AA', 'BB', 'CC', 'DD', 'EE', 'FF'],";
                LineChartData += " datasets: [";
                LineChartData += "{ label: 'Dataset 1', data: [12, 19, 3, 5, 2, 3], borderColor: ['#587ce4'], borderWidth: 2, fill: false},";
                LineChartData += "{ label: 'Dataset 2', data: [5, 23, 7, 12, 42, 23], borderColor: ['#ede190'], borderWidth: 2, fill: false},]}";
                return LineChartData;
            }

    at page.aspx the following code:

    ......
    ......
    ...... 
    <div class="card-body">
    <h4 class="card-title">Line chart</h4>
    <canvas id="linechart-multi" style="height:230px"></canvas>
    </div>

    <input type="hidden" runat="server" id="LineChartData" />

    <script> $(function () { 'use strict'; var multiLineData =document.getElementById("<%=LineChartData.ClientID%>").value; var options = { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, legend: { display: false }, elements: { point: { radius: 0 } } }; if ($("#linechart-multi").length) { var multiLineCanvas = $("#linechart-multi").get(0).getContext("2d"); var lineChart = new Chart(multiLineCanvas, { type: 'line', data: multiLineData, options: options }); } }); </script> </asp:Content>

    Hope anyone can help me to solve this problem ...

    the javascript error saya: 

    Uncaught TypeError: Cannot create property 'datasets' on string '{labels: ["AA", "BB", "CC", "DD", "EE", "FF"],datasets: [{ label: 'Dataset 1', data: [12, 19, 3, 5, 2, 3], borderColor: ['#587ce4'], borderWidth: 2, fill: false},{ label: 'Dataset 2', data: [5, 23, 7, 12, 42, 23], borderColor: ['#ede190'], borderWidth: 2, fill: false},]};

    Saturday, January 5, 2019 1:01 AM

Answers

  • User567064909 posted

    I found the problem .. it is the format of JSON string it should enclosed with double quotes.. and string must be converted to JSON object at the javascript code ...  This example of how to pass JSON string and then convert it to JSON object...laughing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 5, 2019 7:42 PM