Sunday, March 01, 2009

How To Force Partial Postback

ASP.NET UpdatePanel control allows us to program web pages with partial postback. The page still goes through most of its lifecycle stages, but only a portion of HTML is updated in the browser. This is a quick and efficient way to improve user experience by reducing page flicker.

Usually, the events that trigger partial postback of an UpdatePanel are defined declaratively in .aspx file. For example, events by child controls are considered triggers by default. If a control is located outside UpdatePanel, it can still be declared a trigger using markup:

<asp:UpdatePanel ID="MyUpdatePanel" runat="Server">
<asp:AsyncPostBackTrigger ControlID="Button1" />

However, sometimes it is necessary to trigger partial postback programmatically. For example, consider an UpdatePanel that is used together with CollapsiblePanelExtender. We want to force postback when user expands the panel. The logical place to do so is inside the "Expanded" event handler, and the code is very simple:

function onCollapsiblePanelExpanded(sender, args) {
__doPostBack('<%= MyUpdatePanel.ClientID %>', '');

If we need specific server-side logic to handle partial postback, ScriptManager control offers two properties: bool IsInAsyncPostBack and string AsyncPostBackSourceElementID. The former indicates whether page is processing a partial postback, and the latter contains ID of the UpdatePanel being processed.