Tuesday, January 11, 2011

Optimized your AJAX Code using Update Panel – Part I


Optimized your AJAX Code using Update Panel

Update Panel is most common and frequently used control in AJAX.NET. But wrongly used Update Panel can create serious performance issue.

Background:
What ever the controls resides within the Update Panel controls are part of the partial update and every time they are receiving ViewState data for each control those are within update panel.

This is a big overhead as all controls irrespective of part of partial update are getting render and transmit data to-fro on every update.

Myth:
It is good to use UpdatePanel for whole page.
It is good to use single UpdatePanel for a single page.

Solution:
If you are using UpdatePanel for whole page except the postback it is not adding any benefit to your page. In some cases it may increase the partial postback size then actual.

Unknowingly this fact, normal users are creating one update panel in starting of ASPX page and closing it on ending of ASPX Page.

So identify what controls are static and don’t include them in UpdatePanel.

Less control less render output this is a fact of WebPages but for UpdatePanel this will not give any benefit. As mentioned earlier all controls within UpdatePanel are getting render so identify the controls which are dependent on each other, group it and put them in a single Update Panel, repeat this for all Page Control. Like selection of a Country you want to show Cities then put them in a separate UpdatePanel. And selection of CreditCardType show list of CreditCards in a separate UpdatePanel.

This way number of update panel may increase but the rendered partial update/viewstate can reduce.

Use of Multiple UpdatePanel can not solve the problem, as changing on any update panel data all update panels are getting refreshed. (I don’t know what was there in Microsoft Developer’s mind). But thank god they give the alternative.

Use UpdateMode property appropriately for multiple UpdatePanel. Default value for UpdateModel is “Always”

Use UpdateMode = “Conditional” for multiple UpdatePanel

<asp:UpdatePanel ID="UpdatePanel1" runat="server" 
  UpdateMode="Conditional" >

<asp:DropDownList ID="CountryDropDown" runat="server" 
  OnSelectedindexChanged="CountryDropDown_SelectedIndexChanged"
/>

<asp:DropDownList ID="CityDropDown" runat="server" />

</asp:UpdatePanel>   
 

<asp:UpdatePanel ID="UpdatePanel2" runat="server" 
  UpdateMode="Conditional" >

<asp:DropDownList ID="CreditCardType" runat="server" 
  OnSelectedindexChanged="CreditCardType_SelectedIndexChanged" 
/>

<asp:DropDownList ID="CreditCardDropDown" runat="server" />

</asp:UpdatePanel>

You can also use it in nested, master page or in User Controls in same way.

No comments:

Post a Comment