Set jQuery text value is lost after postback

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="../js/jquery/jquery-1.4.1.min.js" type="text/javascript"></script> <script> function btnSetText_OnClientClick() { $("#<%= lbl1.ClientID %>").text("123"); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lbl1" runat="server"></asp:Label> <asp:Button ID="btnSetText" runat="server" Text="Set Text" OnClientClick="btnSetText_OnClientClick(); return false;" /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /> </div> </form> </body> </html> protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { string str1 = lbl1.Text; } 

The script is here, when the user clicks β€œset text”, the jquery script will update the label value, when the β€œSubmit” button is pressed, the value of lbl1.Text is always β€œβ€, which is lost after the postback, any ideas?

+2
source share
2 answers

Use A HiddenField Get value after postback

try it

 <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="../js/jquery/jquery-1.4.1.min.js" type="text/javascript"></script> <script> function btnSetText_OnClientClick() { $("#<%= lbl1.ClientID %>").text("123"); $('#HiddenFileldVariable').val($("#<%= lbl1.ClientID %>").text()); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lbl1" runat="server"></asp:Label> <asp:Button ID="btnSetText" runat="server" Text="Set Text" OnClientClick="btnSetText_OnClientClick(); return false;" /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /> <asp:HiddenField ID="HiddenFileldVariable" runat="server" /> </div> </form> </body> </html> protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { string str1 = HiddenFileldVariable.Value; } 
+5
source

I think the problem may be related to the EnableViewState property for your asp.net button; It must be true in order for the value to be passed to the postback handler.

I checked a little on my side, and I can reproduce your problem if EnableViewState is "false"; It works if I set it to true.

Hope this helps,

Roger

-2
source

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


All Articles