When Building Responsive Web Applications in ASP.NET Web Forms, developers often face the need to refresh only a portion of the page, not the entire layout. That’s where UpdatePanel comes in. This article guides you through:
- How to use UpdatePanel for partial updates
- How it behaves in standalone pages vs. pages using Master Pages
- Best practices and common mistakes to avoid
What is UpdatePanel?
The UpdatePanel control in ASP.NET enables partial-page rendering using built-in AJAX functionality. This means that only the content inside the panel will be updated, reducing page flicker and load time.
1. Using UpdatePanel in a Standalone ASP.NET Page
ASPX Markup
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" Font-Size="Large" />
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update Time" OnClick="btnUpdate_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Code-Behind (C#)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblTime.Text = "Loaded at: " + DateTime.Now.ToString("T");
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
lblTime.Text = "Updated at: " + DateTime.Now.ToString("T");
}
Clicking the button updates only the label — no full-page reload.
2. Using UpdatePanel in a Master Page Environment
When your site uses Master Pages, placing controls like ScriptManager and UpdatePanel requires special attention.
Master Page (Site.Master)
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</form>
Content Page (Home.aspx)
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" />
<asp:Button ID="btnUpdate" runat="server" Text="Refresh" OnClick="btnUpdate_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp: Content>
Code-Behind (Home.aspx.cs)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
lblMessage.Text = "Page loaded at: " + DateTime.Now.ToString("T");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
lblMessage.Text = "Updated at: " + DateTime.Now.ToString("T");
}
Common Mistakes to Avoid
Issue |
Solution |
Adding multiple ScriptManager controls |
Use only one in the Master Page |
Placing UpdatePanel outside ContentPlaceHolder |
Always put it inside <asp:Content> |
Forgetting OnClick method in code-behind |
Define event handlers properly |