Friday, July 11, 2008

ASP.NET AJAX Extensions Update Panel and Triggers

So far we have been using Update Panels with controls inside the Update Panel which initiate the partial page refresh.

What if we want to refresh an Update Panel based on an external event like a Button which is not necessarily a part of the UpdatePanel's content template? Wait ! Dont jump into ugly ways of refreshing the whole page using F5 !

Triggers is your friend in this case. A trigger can be defined within the Update Panel to specify which control needs to trigger a partial refresh for that section.

For that matter, the only 2 tags you can directly place within an UpdatePanel are ContentTemplate and Triggers. If you directly try placing HTML or Web Controls within the UpdatePanel, it will start throwing compilation errors.

Ok, let us jump into code to understand more. As usual copy paste the following HTML Source and Code behind to your page.


Code behind

protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = System.DateTime.Now.ToString();
Label2.Text = System.DateTime.Now.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{ }

Now, when you run this page, you will notice that when you click on the "Refresh" button you will see that the label below the Refresh button gets updated whereas the label above remains with old value.

Couple of interesting things to notice:-

The Button control is defined outside the UpdatePanel unlike our previous samples.
The Triggers contains something called as AsyncPostBackTrigger for which the ControlID is specified as Button1 and EventID is specified as Click. For now, forget the commented PostBackTrigger definition.

The AsyncPostBackTrigger initiates an async call back and the button associated doesnt do a refresh or postback explicitly to execute the code. In fact, the code you place within the Button1_Click event will throw error, if you want to do something like Response.Write.
Though the Button is a normal asp:Button, it doesnt invoke a postback but refreshes the contents of the Update Panel.

Now, if you comment the AsyncPostBackTrigger line and uncomment the PostBackTrigger line, and run the page, you will notice that the whole page refreshes upon clicking on the "Refresh" Button. This works like a normal button although it does update the contents of the UpdatePanel.

In normal cases you would use AsyncPostBackTrigger since it implies the partial page refresh mechanism.