简体   繁体   中英

Change javascript variable from asp.net codebehind on updatepanel refresh

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?

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") .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM