Please navigate to the bottom of the page for Table of Contents

Saturday, May 28, 2011

ASP.NET AJAX using UpdatePanel control

There are many ways to dynamically update the page content without having to load the entire page again. ASP.NET UpdatePanel control is one of the simplest ones where ASP.NET provides all the frontend and backend plumbing for you. jQuery is another way (along with numerous other java script libraries). In this post we will explore the UpdatePanel server control. UpdatePanel enables sections of a page to be partially rendered without a postback.

Before you can use the UpdatePanel control, you will need to create an instance of ScriptManager. ScriptManager takes care of managing ASP.NET Ajax script libraries and script files, partial-page rendering, and client proxy class generation for Web and application services.

The code snippet below shows an aspx page with an UpdatePanel control which allows a user to click a button to update the count on the page. The button actually does a postback to the page to get the data.

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="AjaxUsingUP.aspx.cs"
Inherits="WebApplication1.AjaxUsingUP" %>


<!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>AJAX using UpdatePanel</title>
</head>
<body>
<form id="form1" runat="server">
<!-- required for UpdatePanel -->
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<!-- demo of ContentTemplate -->
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Number of refreshes:
<asp:TextBox ID="tbRefresh" runat="server"
ReadOnly="true" Text="0">
</asp:TextBox>
<asp:Button Text="Refresh" ID="btnRefresh"
runat="server"
onclick="btnRefresh_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

 

The C# code behind for the page to which the postback happens, but does not refresh the page as the UpdatePanel takes care of it.

 

using System;

namespace WebApplication1
{
public partial class AjaxUsingUP : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnRefresh_Click(object sender, EventArgs e)
{
int refreshCount = Int32.Parse(tbRefresh.Text);
refreshCount++;
tbRefresh.Text = refreshCount.ToString();
}
}
}

 

UpdatePanel is a very powerful control and exposes a number of useful mechanisms to make the user experience very AJAXy. This example touches upon the basics of the control. I would recommend reading in depth about the control on the MSDN documentation on UpdatePanel Class.

1 comment: