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 you assign an event handler to a control in jQuery document ready event handler, it is assigned to the control and it works normally.
But if the control is placed inside an AJAX UpdatePanel, 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 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, 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 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
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("click", "#button1", function () {
alert("Button was clicked.");
});
</script>
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<input type="button" id="button1" value="Click Me" />
<asp:Button ID="Button1" Text="Do PostBack" runat="server" OnClick="DoPostBack" />
<asp:Label ID="Label1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Code
protected void DoPostBack(object sender, EventArgs e)
{
Label1.Text = "PostBack done at: " + DateTime.Now.ToString();
}
Screenshot
Demo
Downloads