Why ASP.NET AJAX UpdatePanels are dangerous

AJAX, ASP.NET, Performance By Dave Ward on July 11th, 2007

If you’re like me, it’s hard to resist the lure of tossing a half dozen UpdatePanels on every page and reveling in AJAX goodness. The UpdatePanel makes AJAX trivially easy for anyone to implement, even without knowledge of what’s actually going on behind the scenes.

Unfortunately, that very lack of transparency regarding the mechanics of the client/server exchange makes it all too easy to shoot yourself (or your application) in the foot. Let me give you an example that you’re probably familiar with by now, and thoroughly sick of seeing:

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" ID="up1">
 <ContentTemplate>
   <asp:Label runat="server" ID="Label1" Text="Update Me!" /><br />
   <asp:Button runat="server" ID="Button1" 
     Text="Postback Update" OnClick="Button1_Click" />
 </ContentTemplate>
</asp:UpdatePanel>
protected void Button1_Click(object sender, EventArgs e)
{
  Label1.Text = DateTime.Now.ToLongDateString();
}

Simple enough. Button1 is clicked, an asynchronous request is made for the current date/time, and that is displayed as Label1′s content. As simple as it sounds, take a look at the actual HTTP post and response necessary to accomplish the partial postback:

spacer

spacer

Shocking, isn’t it? To display a 22 character string, that’s an awful lot of data sent and received. Acceptable for infrequently used functionality, but a potential deal breaker in heavy use. Luckily, Microsoft has given us a more efficient way to do this, as part of the ASP.NET AJAX framework.

Page Methods

Page methods allow ASP.NET AJAX pages to directly execute a page’s static methods, using JSON (JavaScript Object Notation). JSON is basically a minimalistic version of SOAP, which is perfectly suited for light weight communication between client and server. For more information about how to implement page methods and JSON, take a look at Microsoft’s Exposing Web Services to Client Script in ASP.NET AJAX.

Instead of posting back and then receiving HTML markup to completely replace our UpdatePanel’s contents, we can use a web method to request only the information that we’re interested in:

<asp:ScriptManager ID="ScriptManager1" runat="server" 
  EnablePageMethods="true" />
<script language="javascript">
 function UpdateTime() {
   PageMethods.GetCurrentDate(OnSucceeded, OnFailed); 
 }
 
 function OnSucceeded(result, userContext, methodName) {
   $get('Label1').innerHTML = result; 
 }
 
 function OnFailed(error, userContext, methodName) {
   $get('Label1').innerHTML = "An error occured.";
 }
</script>
<asp:Label runat="server" ID="Label1" Text="Update Me!" /><br />
<input type="button" id="Button2" value="Web Method Update" 
  onclick="UpdateTime();" />
[WebMethod]
public static string GetCurrentDate()
{
  return DateTime.Now.ToLongDateString();
}

Through this method, we’ve completely eliminated the HTTP POST data that was present in the UpdatePanel’s request, and reduced the response down to just the data we’re interested in requesting:

spacer

Using JSON, the entire HTTP round trip is 24 bytes, as compared to 872 bytes for the UpdatePanel. That’s roughly a 4,000% improvement, which will only continue to increase with the complexity of the page.

Not only has this reduced our network footprint dramatically, but it eliminates the necessity for the server to instantiate the UpdatePanel’s controls and take them through their life cycles to render the HTML sent back to the browser.

While I’m a proponent of the simplicity inherent in the UpdatePanel, I think that it is crucial that we use them judiciously. In any heavy use situation, they are very rarely the best solution.

Similar posts

  • Seamless inline text editing with ASP.NET AJAX
  • AJAX, file downloads, and brs
  • Use jQuery and ASP.NET AJAX to build a client side Repeater
  • 3 mistakes to avoid when using jQuery with ASP.NET AJAX
  • jQuery 1.5′s AJAX rewrite and ASP.NET services: All is well

Share this

Tweet
Save on Delicious

What do you think?

I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.

If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.

23 Mentions Elsewhere

  1. 27 Links Today (2007-07-12)
  2. Update panel case study « Private: .NET + OO concept + RIA(AJAX)
  3. Dream of a journey» Blog Archive » Integrating jQuery with ASP.NET
  4. Why ASP.NET AJAX UpdatePanels are dangerous « DOT NET
  5. Stone Coast Web Design's Weblog - Why ASP.NET AJAX UpdatePanels are dangerous
  6. ‘Mo AJAX Pleeeeez?!!! « Tracy’s Blog
  7. Elegant Code » CheckBox GridView Column with a web service call
  8. ASP.NET AJAX - Why should you prefer web service method calls over page method calls? - Weblog :: Boris Ševo
  9. willcodeforcoffee.com » Blog Archive » Those Dangerous UpdatePanels
  10. Exposing User Control client events to host Page server side - Itai Goldstein
  11. Recomendaciones para la Adopcion de AJAX usando ASP.NET AJAX - SergioTarrillo - RichWeblog
  12. Sergio Tarrillo's Blog -> enhancements : Recomendaciones para la Adopcion de AJAX usando ASP.NET AJAX
  13. Using jQuery Inside A DotNetNuke Module UpdatePanel | //refactor this
  14. Mis problemas con ASP.NET AJAX « Gerardo Contijoch
  15. jQuery Secrets with Dave Ward - Craig Shoemaker
  16. [ASPNET] Evitar problemas de performance con los UpdatePanel « Jesús Bosch
  17. Ajax “Instan” di ASP.NET bagai pedang bermata dua « Tempat Untuk Berbagi
  18. ASP.NET, LINQ, jQuery, JSON, Ajax – Oh my!
  19. ASP.NET, LINQ, jQuery, JSON, Ajax – Oh my! | PIXEL SHOP
  20. ASP.NET AJAX – the good and the bad « Josh Rachner's Thought Spot
  21. Need some ‘JavaScript for ASP.NET developers’ good books and blogs, since AJAX UpdatePanels are performance killers - Question Lounge
  22. Visoft, Inc. Blogs | ASP.NET AJAX Page Methods
  23. ASP.NET AJAX UpdatePanels « Skarach's world

148 Comments

Justin
10:11 am - July 11, 2007

Great post. I knew I was avoiding ASP.Net AJAX for a reason. I have been using Mootools for this very reason. I only want the data I need!

Reply to this comment
Michael
10:44 am - July 11, 2007

Justin, take out the UpdatePanel of the ASP.NET AJAX and the library is still useful.

Reply to this comment
Dave Ward
10:53 am - July 11, 2007

Don’t get me wrong. I’m not trying to turn anyone away from ASP.NET AJAX. I think it’s a great framework if you’re developing on ASP.NET.

I mainly want to illustrate the drawbacks associated with careless use of the UpdatePanel, which aren’t necessarily very obvious at first glance.

Reply to this comment
Steven Harman
11:20 pm - July 12, 2007

Agreed! While using UpdatePanels is not in and of itself dangerous, they are a slippery slope and we should use them judiciously, where they make sense.

Along with the performance issues it’s also important to remember that by hiding much of the mechanics that make AJAX work the UpdatePanels are also taking away much of the control we as developers have over what is happening on the client. But at least there are some ways to regain some of that control without totally throwing UpdatePanels out the window -> stevenharman.net/blog/archive/2007/07/06/use-the-pagerequestmanager-to-get-more-control-of-your-updatepanels.aspx

Reply to this comment
Dave Ward
10:43 am - July 13, 2007

That’s a nice post, Steve.

Handling those two simple events really allows us unlimited UI enhancements. I’m looking forward to Orcas’ client script support to make using them even easier.

Reply to this comment
Sergio Pereira spacer
12:54 pm - July 12, 2007

To add even more, don’t forget that the asynchronous postbacks via UpdatePanel allow you to access the properties of all the other controls, and even update them. In your example, if you wanted to change the color of the label or hide it using your C# code instead of javascript, you could. It’s all a trade off for convenience.

Reply to this comment
Stian
2:08 am - July 23, 2007

Nice post, I definitely agree… :-)
This is the reason we first made Gaia; to make a real Hijax library that was as like ASP.NET itself to use and as efficient to use as possible.
With Gaia you write NO javascript at all! And no Script Manager! And no changes to web.config!
Check out the cool video that is on our landing page. ;-)

Stian

Reply to this comment
Mike
2:27 pm - July 11, 2007

Nice post, but with this kind of title you might scare some people. An asynchronous postback with an UpdatePanel contains about the same amount of data than a normal postback, but it’s not ‘dangerous’ at all.

Also, the second method will not update the ViewState, that is important too. If anything, I think it’s positive that ASP.NET Ajax allows you to go both ways.

Reply to this comment
Dave Ward
4:45 pm - July 11, 2007

You’re definitely right about that. A partial postback will always be more efficient than a full postback would have been to accomplish the same task.

Reply to this comment
Rob
5:30 am - July 12, 2007

UpdatePanels aren’t dangerous, they just need to be used carefully and appropriately. They clearly don’t offer best on-the-wire performance compared to web methods/JSON but they’re better than doing an actual postback!

Reply to this comment
Maxime
9:49 am - July 12, 2007

I think we can make an allusion here. Drinking one beer wont be fatal for you but drinking 25 of them in an hour would put you down. Here is why I brought that up… UpdatePanel need to be used carefully and this example is not a real life example but a minimalistic one (why even use AJAX here :P). On one of my project, I have a Wizard with a MultiView and I want the user to go through the registration process completely without any hassles. Going with the update panel take me an hour. Going with web methods, Javascript and JSON would take me a day without greatly improving the performance (and if it does by only a few bytes). Don’t misunderstand me, I don’t say that JSON and WebMethods are to be thrown… I just say that each have their own way to be used.

Any comments ?

Reply to this comment
Dave Ward
10:12 am - July 12, 2007

Something like your example is a place where an UpdatePanel is well suited. I couldn’t agree more. If for no other reason than the fact that you need ViewState to make those controls work smoothly.

I’ve been seeing more and more questions posted on the ASP.NET forums lately about how “AJAX slowed down my web page”, that usually result from someone deploying a heavy-on-the-wire app that runs great locally but bottlenecks over a WAN link. If they’d read a post like this before planning, they would have been able to avoid the problem completely.

With that in mind, my purpose here is just to highlight the underlying dangers of careless UpdatePanel use, not to discourage use of UpdatePanels across the board.

Reply to this comment
Maxime
10:22 am - July 12, 2007

I totally agree with you. In fact… now application that ran smoothly in locals shall be converted directly to web.

I saw example of people converting a DataGrid of a WinForm directly to a GridView without considering the size of the viewstate and the normally slower speed of a WAN network (talking about thousands of rows with multiple KB of data for each row being transfered). Those were obviously bad representation.

However I would love to see a post from you about this kind of things that people are assuming and don’t think about.

Cheers buddy.

Reply to this comment
Gordon spacer
2:34 pm - July 12, 2007

From your example, I fail to see how the UpdatePanel is in any way dangerous. Maybe verbose, but not dangerous…

Reply to this comment
Dave Ward
2:43 pm - July 12, 2007

When it comes to AJAX, I suppose danger is a relative term. However, needlessly increasing my employer’s bandwidth bill by a factor of 40 would certainly be dangerous to my continued employment.

Reply to this comment
Dave Reed
2:08 am - July 13, 2007

Compare it to the size of a regular postback to update that label, and you can say you’re saving that X% in bandwidth by employing AJAX. :)

Reply to this comment
gpa spacer
12:30 pm - September 10, 2007

ah such hilarity wakes the dormant humor sectors of the grey matter I like to call my “conscious thought machine”

Reply to this comment
adam
9:33 pm - July 16, 2007

Hello, may I ask what tools you used to show the headers post response) information (who on the screenshot)?

Thanks!

Reply to this comment
Dave Ward
9:41 pm - July 16, 2007

I use a FireFox addon called FireBug. I highly recommend it for any web development, and especially AJAX development.

I think Fiddler is the name of a similar addon for IE, if you prefer IE.

Reply to this comment
Anonymous spacer
9:47 pm - July 16, 2007

Big thanks for the quick response and information. I like your blog very much (by the way)

Reply to this comment
Zack Owens spacer
1:00 pm - July 17, 2007

UpdatePanels are so easy… why doesn’t Microsoft just fix them so that they return simple data and not a mishmash of stuff like in part 1 and not just simple text?

Reply to this comment
Dave Ward
4:44 pm - July 17, 2007

Don’t get me wrong. I think the UpdatePanel certainly has its time and place. If you need to modify ViewState asynchronously, it’s almost definitely the best way.

They’re just overused, due to their ease of use and lack of proper warning about how they do their magic. I’m hoping this post will help a few people avoid that pitfall.

Reply to this comment
Anonymous spacer
7:53 pm - July 17, 2007

Hello Dave, I now know how to call the web service and return a string, but is there any way we can return more complex type like image, and how can I replace exist with new image on a web page?

Reply to this comment
Dave Ward
8:21 pm - July 17, 2007

If the image exists on the file system, you could return that URI in your Web Method and then update the image element’s src property in the OnSuceeded handler. For example:

function OnSucceeded(result, userContext, methodName) {
  $get('img').src = result; // Where the Web Method's return is the new image URI.
}

If you need to send a binary file stream with a generated image, you could use an ASHX handler as the src of the image element.

Reply to this comment
Ming
7:28 pm - July 18, 2007

Hi Dave, I tried last night for my dynamic binary image, and out of luck so far (CaptchaImage for register purpose, I allow user to click “try another” link, then ajax refresh and display a newly generated CaptchaImage). I try to use ASHX handler, which it return a image:
// Create a random code and store it in the Session object.
string code = GenerateRandomCode();
context.Session["CaptchaImageText"] = code;

CaptchaImage ci = new CaptchaImage(code, 200, 50);
context.Response.ContentType = “image/jpeg”;
// Write the image to the response stream in JPEG format.
ci.Image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
ci.Dispose();

but I have no luck getting it down to Ajax and display on the page.

also I try direct:
$get(‘captchaimage’).src = “Handler/CaptchaImageHandler.ashx”; it works some times (when I clear the cache), it appears to pick up the cache image rather than download the image from handler.

Reply to this comment
Zack Owens spacer
8:52 pm - July 18, 2007

Why don’t you take a look at Subkismet (www.codeplex.com/subkismet). They have a very nice CAPTCHA handler written for you.

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.