Monday, April 12, 2010

ASP:Label within UpdatePanel does not update when referenced from JavaScript

If you try and update the value of an ASP:Label element from client side javascript code and the label is nested within an ASP:UpdatePanel, then the problem might be the fact a post-back event is resetting the value of the label.

Here is what I had: An asp:UpdatePanel with an asp:label and an asp:button. When the asp:button was clicked a client side script would run and needed to update the value of the label.

Everytime my client event fired and changed the InnerHtml of the label, the page did not show the change.

The problem was that the asp:button was causing an update of the updatepanel which then updated the value of the label from data in the view state.

Here are 2 solutions:

In this case, I should have just used a plain old HTML button (<input type="button" …> ) and this would have not caused the update panel to get updated. (Also, I could have used a simple div element instead of an ASP:Label – but I was also using the label for server side messaging).

But what if you needed the button to perform some server side logic? In this case you could set the UpdateMode of the UpdatePanel to “Conditional” and set the ChildrenAsTriggers property to “false”. Both of these will not allow the update panel to refresh after a post back, thereby not overwriting the values of the label.

No comments: