1

I have some JSON generated in my asp.net codebehind. Initially this data was stored in a Page property string and accessed in the javascript like so:

var myjson = '<%= PageProperty %>'

However, on a postback of the updatepanel, the properties are updated, but the previous values are retained in the javascript variables.

What I ended up doing was assign the json to the Text attribute of a hidden asp:TextBox then retrieving that in javascript like so:

ASP markup:

<asp:TextBox ID="jsonData" runat="server" Text="" style="display: none" />

Javascript:

var myjson = $('#<%= jsonData.ClientID %>').val();

This seems messy (note: there are 15 of these fields removed for simplicity).

Is there are better way of doing this (without 15 ajax calls)?

Why are the updated Page properties not picked up after postbacks?

Chris L
  • 2,262
  • 1
  • 18
  • 33

1 Answers1

1

You can use this to inject the JavaScript script directly from code behind:

Injecting javascript from a user control inside an UpdatePanel

ASP.NET inject javascript in user control nested in update panel

The code of the injected script should update the variables.

You can try a dirty trick: add an <script> tag with code to update the javascript variables in the client side. Put it at the bottom of the update panel HTML. When the HTML is rendered in the browser, the script will run.

If you stuck to the hidden filed trick, you can serialize the 15 values as JSON, and store the serialized value. Then you can use javascript to deserialize the JSON on the client side. On the server side use JSON.NET. On the client side use the javascript funcion JSON.parse("serialized values").

Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117
  • Injecting the JS isn't much use as I want to dynamically change the contents so will be **very** messy. I already tried including the – Chris L Jul 08 '14 at 13:48
  • You can always resort to a hidden field for a variable. ;) – RealityDysfunction Jul 08 '14 at 13:50
  • 1
    So far that's the *slight* lesser of two evils – Chris L Jul 08 '14 at 13:58