ASP.NET Button Control to Trigger Client-side Code which, In Turn, Triggers Server-side Code

StackOverflow https://stackoverflow.com/questions/20669744

  •  19-09-2022
  •  | 
  •  

سؤال

I've seen a lot of related questions, but don't seem to be able to figure out what to do here.

I have an asp hidden field control defined as

<asp:HiddenField ID="hField" runat="server"></asp:HiddenField>

and a button control defined as:

<asp:Button ID="btn1" runat="server" usesubmitbehavior="false" onClientClick="return jsFunc()"/>

The JavaScript function looks something like this:

function jsFunc() {
    document.getElementById( "hField" ).Value = "someString";
    __doPostBack( "btn1", "" );
 }

Finally, in my code behind, I have the following function:

Protected Sub btn1_Click( ByVal sender As Object, ByVal e As System.EventArgs) Handles btn1.Click
    ' // access hidden field hField 
End Sub

but the problem is that the value I assigned to the hidden value in the javascript is not persisting the postback.

What do I need to understand or what do I need to do so that the updated hidden field value persists?

هل كانت مفيدة؟

المحلول

The answer is easy. Javascript is case sensitive, so when you use Value property of hidden element, it creates new property Value instead of setting it to value property.

So, you just need to update code to follow:

function jsFunc() {
   document.getElementById("hField").value = "someString";
   __doPostBack( "btn1", "" );
}

نصائح أخرى

You shouldn't call __doPostBack() from your javascript function. Instead the javascript function should return false in case you want to cancel/prevent the PostBack.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top