Forcing a partial postback from an HTML control
Today I've seen an interesting thread in the AJAX foruns. The problem was how to make a traditional HTML control refresh an UpdatePanel. The answer turned out to be simple. Before showing some code (which could also be written in a slightly different way!), it's important to understand when a partial postbacks happens.
The PageRequestManager intercepts all the postbacks that happen on a page that has UpdatePanels. A partial postback happens when the control that starts this action is placed inside an UpdatePanel or maintained in the async control list (an internal field of the class). The following code uses this info to add a textbox to that list and handles the change event by starting a postback. This is all that is necessary to have a partial postback!
Another thing need was the ability to refresh an UpdatePanel when the partial postback was started by that control. In the code, I perform a simple check and try to see if the responsible for the postback is my HTML textbox. If it is, then I need to update the panel by calling its update method (ie, you're seeing something similar to what happens when you triggers - ie, triggers use code similar to this one).
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (ScriptManager1.IsInAsyncPostBack &&
Request.Params["__EVENTTARGET"] == "txt")
{
panel.Update();
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:updatepanel runat="server" id="panel" UpdateMode="Conditional">
<ContentTemplate>
panel 1: <%= DateTime.Now.ToString() %>
</ContentTemplate>
</asp:updatepanel>
<asp:updatepanel runat="server" id="Updatepanel1" UpdateMode="Conditional">
<ContentTemplate>
panel 2:<%= DateTime.Now.ToString() %>
</ContentTemplate>
</asp:updatepanel>
<input type="text" id="txt" onchange="__doPostBack('txt','');" />
</form>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded( function() {
Sys.WebForms.PageRequestManager.getInstance()._asyncPostBackControlClientIDs.push( "txt" );} );
</script>
</body>
</html>