Monday, January 14, 2008

UpdatePanel: How to force Postback

Ok, time to make a new post. Hopefully no one will notice my last post.

The question this time is: If I'm using the ASP.NET 2.0 Web Extensions UpdatePanel control, how do I force a button inside the UpdatePanel to refresh the whole page?

You know that when you're using the UpdatePanel, any postback that is caused by any control inside the panel, will only refresh the content inside the panel.

But sometimes you want to refresh the whole page. How do you do it? The trick is to use the PostBackTrigger, indicating the button (or any other control) that you want to override the normal UpdatePanel behaviour:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="Button1" runat="server" Text="xpto" OnClick="Button1_Click" />
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="Button1" />
            </Triggers>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

In this example there's a Button inside the UpdatePanel and I want it to refresh the whole page because it updates the value of the TextBox that is outside the panel.

Now let's say that instead of a Button, you have a User Control inside the UpdatePanel and that control has a two buttons inside of it. One of the button does something that updates the content of the user control. The other button needs to refresh the whole page (let's call it PageRefreshButton). Just do the following:

 

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <uc:MyControl ID="MyControl1" runat="server" />
    </ContentTemplate>
    <Triggers>
       <asp:PostBackTrigger ControlID="MyControl1$PageRefreshButton" />
    </Triggers>
</asp:UpdatePanel>

4 comments:

Nick said...

Nice article, exactly what I needed.

Tiago Epifânio said...

Thanks for your feedback, Nick. It's nice to know I'm helping.

Fernando García said...

Hi, I was stuck with this problem too. I have a multiview and needed a full postback for the multiview to change. The postback button was in a grid that I needed inside the updatepanel and couldn't figure out how to achieve that.

Thanks for your article! Saved my day!!

Jason Dufair said...

Thank you!