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
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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", "" );
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top