In this article I will explain how to solve the problem of jQuery DatePicker not working inside ASP.Net AJAX UpdatePanel after UpdatePanel’s Asynchronous request or Partial PostBack is completed.
Cause
All jQuery plugins are applied on the Page Load event of the HTML Page or in other words document ready event which is fired when the whole page or document is rendered completely in browser. Now jQuery assigns a unique identification to all controls when applying the plugin. But when some control is inside UpdatePanel and a Partial PostBack occurs the Unique Ids assigned by jQuery is lost and hence the plugin stops working.
The Solution: Making jQuery DatePicker work inside ASP.Net AJAX UpdatePanel
Below is the jQuery DatePicker plugin implementation, placed inside ASP.Net AJAX UpdatePanel. The jQuery DatePicker is applied to the ASP.Net TextBox using the SetDatePicker JavaScript function.
The SetDatePicker JavaScript function is called at two places, first inside jQuery document ready event handler and second inside the ASP.Net AJAX UpdatePanel endRequest event handler.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
rel="Stylesheet" type="text/css" />
<script type="text/javascript">
//On Page Load.
$(function () {
SetDatePicker();
});
//On UpdatePanel Refresh.
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
SetDatePicker();
}
});
};
function SetDatePicker() {
$("[id$=txtDate]").datepicker({
showOn: 'button',
buttonImageOnly: true,
buttonImage: 'calendar.png'
});
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Select Date:
<asp:TextBox ID="txtDate" runat="server" />
<hr />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
</ContentTemplate>
</asp:UpdatePanel>
Fetching the selected item on Server Side
The selected date can be fetched on server side inside the click event handler of the Button from the Request.Form collection as shown below.
C#
protected void Submit(object sender, EventArgs e)
{
string selectedDate = Request.Form[txtDate.UniqueID];
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Selected Date: " + selectedDate + "');", true);
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim selectedDate As String = Request.Form(txtDate.UniqueID)
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "alert", "alert('Selected Date: " & selectedDate & "');", True)
End Sub
Screenshot
Demo
Downloads