Update panel helps with ajax in asp.net. It registers itself with the script manager and perform a
partial postback
without refreshing the whole page. However at the
code behind there is a full round trip of the page and control events takes place
. This will be a performance hinderance if the code behind is not designed ajax friendly. So simply adding update panel not simply enhance user experience even though it keeps the page responsive.
Let us try a worst case example.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager EnablePartialRendering="true" ID="Script1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<contenttemplate>
<asp:TextBox ID="Text1" runat="server">
<asp:Button runat="server" ID="Button1" Text="Partial Postback" OnClick="Button1_Click"/>
</contenttemplate>
<asp:TextBox ID="TextBox1" runat="server" CausesValidation="false" OnTextChanged="TextBox1_TextChanged" >
<asp:Button ID="Button2" runat="server" Text="Full Postback" />
The above markup has a
Script Manager
where
Partial Rendering
enabled. It has an update panel with a textbox and a button. Outside the update panel there is a textbox which has a
Text_Changed
event handler declared. The button inside the update panel
do a partial postback on its click event
and update the textbox inside the update panel. This is the desired behaviour.
protected void Button1_Click(object sender, EventArgs e)
{
Text1.Text = "This is updated by partial postback";
}
But we don't need the
Text_Changed
event handler job here as it is no way related to our partial postback. But unfortuantely it executes even on the partial postback. For our test case the Text Changed event handling a busy function.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(20000);
}
So Changing the textbox and hit the button inside the update panel takes 20 secs to get the response.
. This is simply unnecessary because our update panel event don't need to run the Text changed event.
So the good thing we can do is
move the handler assignment to code behind
<asp:TextBox ID="TextBox1" runat="server" CausesValidation="false" >
protected void Page_Load(object sender, EventArgs e)
{
string id = Script1.AsyncPostBackSourceElementID;
if (string.IsNullOrEmpty(id)==true)
{
TextBox1.TextChanged += new EventHandler(TextBox1_TextChanged);
}
else
{
}
}
The above code identify the async postback by checking the
AsyncPostBackSourceElementID
of the script manager and it assign handlers or function calls accordingly.
Conclusively, care needs to be taken when using update panel to make the asynchronous postback a better experince. Cheers.