In this article I will explain with an example, how to solve the issue of
jQuery event handler inside
AJAX UpdatePanel not working after Partial PostBack in ASP.Net.
Cause
When control is assigned with an event handler inside the
jQuery document ready event handler, it is assigned to the control and it works fine.
But if the control is placed inside an
AJAX UpdatePanel then after partial PostBack the event handler gets removed, which ultimately causes it to stop working.
Solution
The solution to this problem is to make use of
jQuery ON function to assign event handlers as it makes sure that the event handlers are retained even if they get removed by some other activity like Partial PostBack.
Prior to
jQuery ON function,
jQuery live was being used which also worked in similar way, but due to some drawbacks
jQuery has depreciated from the 1.9+ versions.
jQuery on Syntax
Example
Following is an example in which I have an HTML Button and an ASP.Net Button inside
AJAX UpdatePanel.
To the HTML Button I have assigned an
OnClick event handler using
jQuery for which I have specified BODY as the parent element.
Note: Parent Element must be always outside the
AJAX UpdatePanel. You can also specify UpdatePanel as the parent element but then you will have to place the script below the UpdatePanel otherwise it will not work. Hence to be on safer side always specify the BODY as the parent element.
The ASP.Net Button does a Partial PostBack and has a Server-Side event handler which displays the time of PostBack in a Label control.
HTML
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("click", "#btnClickMe", function () {
alert("Button was clicked.");
});
</script>
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<input type="button" id="btnClickMe" value="Click Me" />
<asp:Button runat="server" Text="Do PostBack" OnClick="DoPostBack" />
<br />
<br />
<asp:Label ID="lblMessage" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Code
C#
protected void DoPostBack(objectsender, EventArgs e)
{
lblMessage.Text = "PostBack done at: " DateTime.Now.ToString();
}
VB.Net
Protected Sub DoPostBack(sender As Object, e As EventArgs)
lblMessage.Text = "PostBack done at: " & DateTime.Now.ToString()
End Sub
Screenshot
Demo
Downloads