Isaac Kleinman
Isaac Kleinman

Reputation: 4452

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

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?

Upvotes: 0

Views: 850

Answers (2)

Sergey Litvinov
Sergey Litvinov

Reputation: 7478

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

Upvotes: 2

M4N
M4N

Reputation: 96626

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.

Upvotes: 1

Related Questions