javascriptasp.netascx

Passing Data to client side (javascript) in post back in .ascx page


There is devExpress dxchart in ascx page.

asp:UpdatePanel ID="UpdatePanel1" runat="server"  UpdateMode="Conditional">
   <ContentTemplate>
    <br />
        <div id="trendChart" style="height: 500px;   width: 100%;"> </div>
    <br />
   </ContentTemplate>
</asp:UpdatePanel>

Data is loading fine in Page_Load method. But when button click is used and chart data is not getting updated. It shows old values as were in Page_Load.In button click following code is used.

    NewData = jsonData

 System.Web.UI.ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "ANY_KEY" + 
 Guid.NewGuid.ToString, "UpdateChart();", True)

'NewData' is public property. The UpdateChart in javascript is below.

function UpdateChart()
{
  myData = '<%= NewData%>';
  alert('tesing');
  var parseObj = JSON.parse(myData);
  $(function () {
    $("#trendChart").dxChart({
        dataSource: parseObj,
        series: {
            argumentField: "Month",
            valueField: "Value",
            name: "Value",
            type: "bar",
            color: '#ffaa66'
        }
    });
  });
}

when button click is done 'NewData' is nothing in UpdateChart() (javascript) and chart still shows old values.


Solution

  • You could pass the data as a property of the UpdateChart-function and then some other adjustments to your code.
    First create an init-dxChart-function. This function can be called on first load of page and when you update your data.

    function InitChart(dataForChart) {
        $("#trendChart").dxChart({
            dataSource: dataForChart,
            series: {
                argumentField: "Month",
                valueField: "Value",
                name: "Value",
                type: "bar",
                color: '#ffaa66'
            }
        });
    }
    

    Second change your UpdateChart-function, so that it gets a parameter:

    function UpdateChart(myData) {
      var parsedData = JSON.parse(myData);
      // Call Init Chart function here
      InitChart(parsedData);
    }
    

    Third: Change your server-side-javascript, so the data is passed to the function:

     System.Web.UI.ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "ANY_KEY" + 
     Guid.NewGuid.ToString, "UpdateChart(" + jsonData + ");", True)