Introduction
ASP.NET UpdatePanel
control allows to build rich, client-centric Web applications. UpdatePanel
controls refresh only selected part of the page instead of refreshing the whole page with a post back. In another words, this is performing a partial-page update. A Web page that contains a ScriptManager
control and one or more UpdatePanel
controls can automatically participate in partial-page updates, without custom client script.
When using JavaScript or jQuery in UpdatePanel
enabled web page, everything will work fine at the first page load, but after any asynchronous post back happens by UpdatePanel
, all JavaScript and jQuery effects will vanish.
Why is this Happening?
Because when the UpdatePanel
post back triggers, the existing markup will overwrite with the markup generated by UpdatePanel
on the post back, which destroys all event handlers from HTML elements in the UpdatePanel
.
What are the Solutions?
There are a couple of ways to fix this. In this article, IMO the easiest solution for this problem is to use Sys.Application
inside UpdatePanel
to call JavaScript, jQuery functions after each Asynchronous post back event.
Example
In the example below, I used an asp button for post back event and jQuery to show a message when Click Me! link is clicked.
JavaScript/jQuery function:
<script type="text/javascript">
function jScript() {
$("#click").click(function () {
alert("Clicked Me!");
});
}
</script>
ASP.NET UpdatePanel
with JavaScript/jQuery re-call function:
<%----%>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<%----%>
<%----%>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<%----%>
<ContentTemplate>
<%----%>
<script type="text/javascript" language="javascript">
Sys.Application.add_load(jScript);
</script>
<%----%>
<%----%>
<asp:Button ID="btnPostBack" runat="server"
OnClick="btnPostBack_Click" Text="Click To Postback" />
<%----%>
<%----%>
<a href"#" id="click">Click Me!</a>
<%----%>
</ContentTemplate>
<%----%>
</asp:UpdatePanel>
<%----%>
ASP.NET (C#) code for button:
protected void btnPostBack_Click(object sender, EventArgs e)
{
btnPostBack.Text = "UpdatePanel PostBack Happened";
}
Conclusion
After calling JavaScript/jQuery functions inside UpdatePanel
using Sys.Applicaiton.add_load()
event handler, you will be able to solve the problem.
Feel free to comment, suggest or give your feedback.
The post jQuery $(document).ready is not Working in UpdatePanels – ASP.NET appeared first on Noor Ahmad Feroozi's Blog.