ASP.Net metric value changed in jQuery but no change in postback

The initial value for the ASP.Net label is "xyz".

I changed the ASP.Net label value as shown below:

$("#<%= lblNew.ClientID %>").text("123"); 

It has changed on the web page. But when I click on the button and get the label value, it goes back to the previous value "xyz" instead of "123".

 Response.Write(lblNew.Text); 

I tried to set html tags instead of text, as shown below: but it doesn't work either.

 $("#<%= lblNew.ClientID %>").html("123"); 

How can I change jquery value? Thanks.

+4
source share
4 answers

This is because the text value of the label is loaded from the view state. Your jquery changes the value of the label, but does not change the state of the view when its value is loaded during the postback .... But you want the text of the change label, so you can get it like this:

 string lblvalue=Request[lblNew.UniqueID] as string; 

Here's an example to understand how view state with a label works ... refrence MSDN

 <asp:Label runat="server" ID="lblMessage" Font-Name="Verdana" Text="Hello, World!"></asp:Label> <br /> <asp:Button runat="server" Text="Change Message" ID="btnSubmit"></asp:Button> <br /> <asp:Button runat="server" Text="Empty Postback"></asp:Button> And the code-behind class contains the following event handler for the Button Click event: private void btnSubmit_Click(object sender, EventArgs e) { lblMessage.Text = "Goodbye, Everyone!"; } 

illustrates the sequence of events that occur, highlighting why a change in the Label Text property should be stored in view state. enter image description here

+6
source

To solve the problem you are facing, use a hidden field and update its value along with the label field. When the postback happens, you can read the updated value from the hidden field

+2
source

Try .val() instead

 $("#<%= lblNew.ClientID %>").val("123"); 

The documentation can be found here: http://api.jquery.com/val/#val-value

EDIT:

I read your question incorrectly and .text should be ok. I think the problem is more with postback. Can you confirm how the code is called $("#<%= lblNew.ClientID %>").text("123"); ? If it's on $(document).ready() , then that should be fine. But this is the result of an action that will be lost when performing the postback / DOM reboots.

+1
source

You cannot change ASP.Net tags in Javascript / JQuery and expect them to be preserved upon postback.

Only values ​​from input controls (for example, text fields, radio controls, radio buttons, etc.) are output to the server.

+1
source

Source: https://habr.com/ru/post/1488258/


All Articles