Why ASP.NET AJAX UpdatePanels are dangerous
AJAX, ASP.NET, Performance By Dave Ward on July 11th, 2007If 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:


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:

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
What do you think? Your comments are welcomed.
I appreciate all of your comments, questions, and other feedback, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums. If you post there and then contact me with a link to the post, I'll try to take a look at it for you.
If you're replying to an existing comment, please use the threading feature. To do this, click the "Reply to this comment" link underneath the comment you're replying to.
Trackbacks
- 27 Links Today (2007-07-12)
- Update panel case study « Private: .NET + OO concept + RIA(AJAX)
- Dream of a journey» Blog Archive » Integrating jQuery with ASP.NET
- Why ASP.NET AJAX UpdatePanels are dangerous « DOT NET
- Stone Coast Web Design's Weblog - Why ASP.NET AJAX UpdatePanels are dangerous
- ‘Mo AJAX Pleeeeez?!!! « Tracy’s Blog
- Elegant Code » CheckBox GridView Column with a web service call

Comments
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!
Justin, take out the UpdatePanel of the ASP.NET AJAX and the library is still useful.
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.
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 -> http://stevenharman.net/blog/archive/2007/07/06/use-the-pagerequestmanager-to-get-more-control-of-your-updatepanels.aspx
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.
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.
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
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.
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.
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!
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 ?
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.
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.
From your example, I fail to see how the UpdatePanel is in any way dangerous. Maybe verbose, but not dangerous…
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.
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. :)
ah such hilarity wakes the dormant humor sectors of the grey matter I like to call my “conscious thought machine”
Hello, may I ask what tools you used to show the headers post response) information (who on the screenshot)?
Thanks!
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.
Big thanks for the quick response and information. I like your blog very much (by the way)
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?
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.
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?
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:
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.
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.
Why don’t you take a look at Subkismet (http://www.codeplex.com/subkismet). They have a very nice CAPTCHA handler written for you.
Try changing your .src assignment like this:
That should avoid any caching issues. It will append a dummy querystring argument with the number of milliseconds since 1/1/1970. This will convince the browser that it should load a fresh copy of the image on every load.
Alternatively, I believe you can use “Response.Expires = -1″ in your image handler, to let the browser know it should never cache the image.
Thanks Dave, using appended milliseconds worked.
also I am using the ASP.NET AJAX Web Service for user registration, I came across a article regarding the security of the web service (http://weblogs.asp.net/despos/archive/2006/10/17/Careful-with-Web-Services-in-ASP.NET-AJAX.aspx)
which suggest not to use AJAX web service for security reasons. I wonder what is your opinion on the web service security for ASPNET Ajax.
I think he’s right to raise the issue, but perhaps a little bit too paranoid. You can secure web services in the same ways that you can secure other HTTP transactions. SSL, cookie/session based authorization, etc.
For example, you could easily check User.IsInRole() for proper access rights before returning any business sensitive data, and encrypt it both ways through SSL.
21ms vs 16ms? I mean that’s alot granted and there is alot more bytes being passed, but come on… dangerous? A little much if you ask me. The whole point of partial postbacks is that you have a bunch of stuff on a page that doesn’t need to be updated. Therefore you aren’t passing more data, your passing less in reality. Additionally, more than likely if you’re going to do anything with the framework on .NET you need the functionality that the UpdatePanel brings vs. the pure javascript. Just my two cents.
Unless you plan on not allowing remote connections to any of your applications or only serving users with OC48s, those response times aren’t very meaningful to compare. All of that communication happens at the 4gb/s bandwidth of my local RAM. In practice, you end up with this sort of situation.
It was actually a real world scenario that prompted me to post this. I’ve inherited an application at work that takes a 153kb partial postback to begin editing a GriwView row. Via LAN, it’s sluggish, but usable. Via WAN/VPN, it’s unacceptably slow.
Keep in mind that you still pass the entire page’s POST information both ways, including full ViewState. Even if you’re only updating a single element, this overhead is incurred. Uploading a large ViewState over the average user’s WAN link is non-trivial.
Not to disagree with this article in general, but it’s a bit misleading to call out how expensive posts via update panel are. The size of an Update Panel postback is just about the same as a regular postback. The response on the other hand is actually (usually) much smaller than the response from a typical postback response. In addition to the smaller size, since the rest of the page doesn’t reload, you get less requests to the server for images, scripts, stylesheets, etc etc etc. I would say in general, update panel postbacks are better for server performance than regular postbacks. I don’t have any numbers or studies to back that up, but it makes sense.
The issue isn’t that Update Panels are expensive, because in many ways they are actually less expensive than the full postback alternative.
The issue I think you mean to call attention to is that if all you want to do is update the value of a little label on the form, a postback in GENERAL is very expensive vs. alternative methods (such as webservices) — whether that be a regular asp.net postback or an update panel postback.
People tend to blame UpdatePanel though I think in part because it’s so easy to wrap an UpdatePanel around this would-be scenario and call it done, not really realizing that you’re really still doing a full postback. That’s true I suppose.
I agree that partial postbacks are more efficient than full postbacks. Though, the upline payload is the same for both, which is the greatest majority of your average DSL/cable user’s transfer time.
My purpose here isn’t at all to discourage UpdatePanel use across the board. What I want is to make people more aware of 1) the specifics of the partial postback implementation and 2) the fact that there are vastly more efficient alternatives in many situations.
Maybe the UpdatePanel is just too good. It’s so easy to use that it encourages novice developers to greatly increase the number of postbacks their pages generate, without even realizing that’s what they did.
UpdatePanels are great when you understand how to use them. I started working at a company a few weeks ago and revamped their AJAX apps. They had previously thrown everything into one UpdatePanel and the updatemode was not set to conditional. Yikes!! It was nearly as bad as a page refresh. If you’ll need multiple things updating within your page I would suggest placing only the necessary components within the panel and attaching only the necessary triggers.
Dave, Thanks for the post and the link.
You clearly show that by not using an UpdatePanel theres a lot of improvement in the amount of data that is passed for the entire HTTP round trip.
I have another clarification..
As ASP.NET developers, we are now used to developing pages using the plethora of ASP.NET server side controls like GridView, DetailsView etc
So will we have to change the way we need to develop pages if we need to use AJAX?
For example we need to display Grid like data, which also enables editing and deleting of records. In that case we use a GridView control in ASP.NET 2.0, Inorder to AJAX enable it i use the following option
1) Using the UpdatePanel control and placing the GridView control inside it.
Thatz the only option i know for such a scenario. And the amount of data that goes back and fro can be a lot as we have a Grid here.
What are the other - ‘Non Update Panel’ techniques of achieving the same?
All the examples i know just show client side Javascript calling a WebService method or a Method in a server side page which returns a string to Javascript
Does anyone have any ideas?
I think there are still many scenarios where it makes sense to use an UpdatePanel (like the one you describe). It’s just important to understand the drawbacks and use them judiciously.
In the GridView editing situation, the best course of action is probably to stick with the UpdatePanel, but optimize your ViewState and page life-cycle as much as possible.
The Update Panel technique is ok when doing updates of Grids and where there are changes of big areas of the page. But very often you just want to set a label or a text box with a new text, fill a DropDownList with new values. What you really want to do is to program this the way you are familiar from ASP.NET with only event handlers in your code behind. And you don’t want to write JavaScript for such operations.
We have developed Gaia which is a great Ajax framework for ASP.NET 2.0. Gaia has taken the best from the ideas of Anthem (which seems to be dead) and added the missing part that made Anthem mediocre.
This means:
* Gaia never looses state on the client
* no need to write JavaScript
* no ScriptManager necessary
* no UpdatePanels necessary
Take a look at it, it both have a GPL and a commercial license.
http://ajaxwidgets.com/
:-)
Stian
Hi All,
If anyone has experience can they shed light on
what is the difference between using PageMethods and ajax.net(www.AjaxPro.info).
And is it possible to return custom class, to the client?
Thanks
Manish
From what I understand, the PageMethods portion of ASP.NET AJAX and AjaxPro are very similar in implementation and functionality.
Check out the JavaScriptSerializer class for information about passing custom classes via JSON in ASP.NET AJAX.
Thanks Dave for your swift response.
Am I right in the following thinking:
Ajax.Net Pro can call methods not only in the Page Class but also Functions in App_Code and Bin (Business and Data Access Layers) Where as MS Ajax PageMethods can only call codebehind or inline functions.
Also the demo at Ajax.Net Professional (Press RunTest Button) show quiet an impressive data type handling including binary files.
Your feed back would be appreciated.
Ajax Pro also provides tools to expose your methods to the web. (It needs some work :)… but that’s a piece of functionality that Ajax Pro handles for you).
Ajax Pro, on the down side, hasn’t been moving as a project. Last changeset was quite a while ago.
I would give Ajax Pro a try. It’s good stuff.
I’ve kinda disliked UpdatePanels for a while now, based a good deal on the kind of analysis Dave shows here.
Something that I’d like to point out to folks in the “it’s not worse than a regular postback” camp is the thought that, yes, for the scenario described above it’s the same as a regular postback (or better) in terms of wire usage… it’s impacting designs in ways beyond the regular form post pattern of submission.
Many design patterns that folks use in non-updatepanel apps are frequently attempted in updatepanel-driven apps (e.g. use of the Timer to simulate continuous feed, using many hidden forms that independently reveal themselves, and so on) that result in partial postbacks happening more frequently than a full postback would have ahd the app been designed in a more ‘classic’ asp.net fashion.
Further, I’d submit to you that with with an updatepanel-based POST, the page has to go through all or most of its regular page lifecycle (control creation, viewstate, stream writing, etc) *plus* it has to reformat the response to match the pipe-delimited format expected by the updatepanel callback. That’s going to result in more overhead *on* the server on a per-request basis.
Paul
You didn’t get a 4,000% improvement — more like a 50% improvement.
I say this because the highlighted text was not the only text in that server round-trip. And, just because you did not see the text does not mean it’s not there.
The exact amount of text on your round trip depends on a lot of details not mentioned here (like: what cookies does the site use?).
Anyways… just be careful with your optimizations (try to be sure they are not premature).
A few minutes spent skimming the asp.net forums makes it very clear that this isn’t a case of premature optimization. A lot of people in real world scenarios are having trouble (or are working their way toward trouble) directly caused by this issue.
Mmmm… use webServices and PageMethods it’s quite nice on the server side, the pain on the neck it’s to update the client side using DHTML, updating a lable it’s fine, but updating a whole set of controls gets complicated.
What you have shown is just a tip of an iceberg. In “real” applications, imagine having to send /receive the complete ViewState back and forth with EVERY request/response. To compute ViewState, ASP.Net renders ALL HTML [and throws away the unwanted HTML using a NullStream] everytime. One alternative is what you’ve shown and even that has the limitation of having to generate “JavaScript proxy” dynamically. I rather prefer a statically rolled Proxy to which I can control cache-policy.
Another approach could be to use Classic Cross Page Posting [Nope, not the ASP.Net Cross page posting; this is just like good old ASP days where you could post to a different page].
I’m interested in returning a large dataset from my code behind file(C#), and binding it to a DataGrid on the client. My preffered method would be to convert the dataset values into JSON, and bind it to a YUI library DataGrid. Anyone know of any examples to get me started? ALL i have found online are simple hello world text examples, but nothing regarding large datasets. Also, if there is a better way of handling this please let me know.
Support for directly serializing a DataSet/Table/Row to JSON for web service and page method calls is coming soon. You can read more about that on Dave Reed’s Blog.
Until then, converting your DataSet to a 2D array and returning that is your best bet.
I didn’t think javascript supported 2D arrays? What are your thoughts on using XML instead? Do you know of any examples or books using your suggestions?
Thank you for the quick response!
JavaScript does support multi-dimensional arrays. They can be defined like this:
or (this is the JSON notation):
Personally, I would use JSON over XML. It’s much easier to work with in JavaScript, and more compact over the wire.
Hi,
I think its all about what is requirement. In Some cases using UpdatePanels is better than Web Methods.
Each has its own pros and cons.
Is there any way I can post back my viewstate with web methods ??
Unfortunately, not very easily.
ViewState is one of the most accurate indicators of whether you should use an UpdatePanel or not.
If you absolutely must access the ViewState in your async operation, then you probably should use an UpdatePanel for that function.
If you can find a way to perform the function without ViewState, then you don’t need an UpdatePanel for that.
Hi,
I was searching the web and found this very interesting article.
I would like to make a question that I don’t know if is even possible: I’ve a dropdown and a treeview (asp.net 2.0 controls) inside a tab panel (asp.net ajax control).
I want to update the treeview when the selected item of the dropdown changes.
If I do this the “traditional” way (autopostback, even inside update panels) I get errors because these controls are inside a tab panel and I supposedly need to re-generate each tab on every postback (some strange issues, I know).
So, I’ve though of using a web method to generate the treeview control code (html) and then put it in the corresponding div. This way, I wouldn’t need to postback so my tab panels wouldn’t disappear and need to be regenerated (or so I think…).
Can anyone tell me if this is even possible (sending the html code of a treeview and updating the correct div on the client)?
The technique Joe explains in this video might be right along the lines of what you’re after: http://asp.net/learn/ajax-videos/video-120.aspx
I got my feet wet with Michael Schwartz’ AjaxPro, so when Ajax.Net came out the early adopters at my company were showing me all of this stuff using the Update Panels. I was not very impressed with the incomprehensible objects required on the server to create the client-side functionality, the fact that these post back. Microsoft touts this as an advantage. NOT!!!
I was pretty sure they were very verbose based on how slowly they appear, but a nearly two-orders of magnitude difference really is pretty convincing to me that they shouldn’t be used at all. I finally found the real Ajax inside Ajax.Net and I couldn’t be more pleased with the way it performs and at the ease of use.
BTW, the form for this comment posting is a bit messed up in IE7.
I want to be able to select a value in a dropdown and based on the item selected enable or disable a textbox without using the update panel. can you help please?
if you have a drop down list with id=”ddlItemList” and a Textbox “tbTextItem” this would be all it take. No ajax required, just clientside scripting.
Note: If you are using a asp.net masterpage or control, you will have to use the client name of the control.
function ListChange()
{
var value = document.getElementById(”ddlItemList”).value
var myTextBox = document.getElementById(”tbTextItem”);
switch (value)
{
case “Yadda”: case “Badda”: case “Bing”:
myTextBox.disabled = false;
break;
default:
myTextBox.disabled = true;
break;
}
}
I usually change the css class of the item to something that shows that the textbox is disabled more clearly:
myTextBox.className = “dis”;
//(with “dis” a css style that makes the textbox background grey)
You will have to run this script on an appropriate event, such as “onChange”.
In the code behind file (C# in my case) you can specify this by writing:
ddlItemList.attributes.add(”onchange”, “ListChange()”);
Geoffrey, i am attemping to impliment but having some issues. im have tried using standard textboxes and html input (text) and neither one works. with the standard text boxes it doe snot like the work return in “RETURN ListChange()”. with the html textboxes it just get an error that says object expected. i am attemping to use html input text field within a tab contol.
It seems to me that generally an updatepanel should be used and web methods should be used in specific cases. There is a definitely a large percentage in bandwidth savings, but people seem to ignore the absolute numbers. If something is 10 times faster but only saves me 100ms, I’m not that concerned. Considering the vast majority of our visitors have DSL or faster, you have to save a lot of bandwith before it’s noticeable. I would consider the WAN/VPN cases to be very specific.
It seems to me that full postback is easy to code but slow.
Updatepanel is faster but a little harder to code.
Web method is fastest and hardest to code.
For me it comes down to development time/code efficiency.
In my experience, the difference is actually more pronounced in real world applications. I’ve got a page at work with a GridView that takes 2-4 seconds to perform any partial postback, over 768/6.0 DSL.
Hello,
I have a radio button list. Based on what the user selects I want to either show or hide controls.
The update panel seems to take 2-3 seconds to reload. Which is way too long. Should I add a onClick JS event to the RadioButton List that would hide or show the controls instead or using the UpdatePanel?
You can definitely do that. You can use something like:
If you want to show and hide groups of controls, contain them in a div, and use the same code on that div instead of the individual control elements.
Just keep in mind that changes you make on the client side won’t be persisted through a postback (or partial postback), and plan accordingly.
How much work is involved when I need to re-populate a GridView server control using Web Method compared with Ajax UpdatePanel?
If you are concerned about posting large viewstates between client and server i advise you to consider implementing a persisted viewstate mechanism (load/reload viewstate from FileIO or other storage). That way no viewstate is send to the client and viseversa.
Hi David,
Nice article. I’ve been working on an AJAX enabled project for a while, and I have been reading many articles. Yours is one of the few that do not endorse everything Microsoft produces.
Anyway, here’s my question: what application are you using to view the request and response data? I’ve been testing http sniffers, but they do not suffice my requirements. I think that you’re using a browser plug-in, but can’t find which one. Please let me know.
Hi, Johan. I’m glad you found the article helpful.
The addon I’m using in those screenshots is FireBug for FireFox. I very highly recommend it to anyone working with AJAX.
Nice article!
It solved an issue I was having attempting to use Client-side callbacks on a page with an UpdatePanel (it would randomly generate the “The state information is invalid for this page” error).
Using PageMethods accomplishes what I need to do without requiring any type of postback which makes my page much more efficient and avoids the error mentioned above. Sweet!
Hi,
I am new in .net.
Can you tell, how to see my page post and response like the above picture? Which tools will help me to show this result?
Reply pls.
Thks,
Kannan.
The FireBug addon to FireFox is what I used for that.
Well, i think it totally depends on situation. If i want to have gridview with a nice look when update its value, how to use webservice or any rpc to complete this work ? yeah i know it is possible to create a full client-side gridview, but how many hours or days and how many budget to finish the job ???
Although the method provided here can dramatically reduce the amount of data being sent back and forth between the server and the client, UpdatePanels, by their very nature, still help improve the performance of an ASP.NET page.
Remember those days when you actually had to request the whole page every time a simple event took place on the page? And the Web used to work fine back then, too. Now, I think we are taking it too hard. Using UpdatePanels is still better than not using them at all and preferring traditional ASP.NET pages.
I still prefer the simplicity of using UpdatePanels. Since I’ve been creating old-fashioned ASP.NET pages with no Ajax capabilities, I find UpdatePanels quite economical. Correct me if I’m wrong.
Update panels are OK if you just have a couple of them. On a complex project, such as the one I just contributed to, all of the other developers used update panels, up to dozens of them per page.
They are very slow. Even on a fast computer && connection, there is several-second wait for updates that would take less than a half-second with real Ajax. In comparison my own pages where I have a dozen or so interconnected REAL ajax objects running on the page are quite fast, and they are orders of magnitude easier to debug, since very little of the code runs inside the over-abstracted ASP.net client-side javascript.
The overly abstracted methods to attach client side events with update panels are also really difficult to read and use, and generate a lot of complexity just for simple tasks.
One of the developers on this project had a weird adversion to writing even a single line of javascript and as such leveraged his considerable knowledge of DOT net to amazing levels of complexity to avoid writing any client side code.
The result was a mess, despite all of his amazing brilliance. He had the same somewhat accusatory tone as the post I am responding to here, “You must not be doing it correctly” when I was trying explain that all was not good about this approach.
TheAgent–
Have you done any benchmarking to support that updatepanels still help the performance of ASP.net pages? I think you’ll find that it’s an incorret statement.
It’s not just about bandwidth. In order for updatepanels to do their magic, the page postback still occurs the exact same way; the only difference is that it’s sent using XHR. On the server, the whole page lifecycle occurs, soup to nuts, before the asp.net ajax engine steps in to parse the response into the pipe-delimited format that updatepanels expect on the client. On the client, the browser’s javascript engine has to then take that response and parse it out to all the updatepanels on the page, which decide whether to update or not based on the parameters you’ve set, among other things. There’s also potentially some memory management issues, depending on how much ’stuff’ is being sent back and forth.
So, there’s some overhead there, on both ends of the pipe. Then, add in the fact that the *perception* is that these things are ‘lighter’, so folks try and squeeze more on there, or are more frequently sending posts back to the server, or possibly are using the AjaxTimer feature to do polling, etc, all of which impacts not only server resources and client memory, but also the pipes, since most browsers have a limited set of TCP connections that they’re willing to have open at any given time. (2 by default for IE, for example).
the insidious threat here is that because they’re so easy to add to the page, developers don’t have to go through as rigorous a design process, which makes it easier to build a crappy appy. It reminds me of the reason why the qwerty keyboard was invented… the story I heard is that it was designed *specifically* to slow down typists back int he days of the manual type to make it harder for them to jam together the type arms.
Just my opinion.
I agree strongly with this. I participate in a lot of threads on the ASP.NET forums, and that’s a very common theme there.
Especially when the Timer comes into play. It just begs a novice developer (especially one with a background in WinForms) to design things wrong.
Thanks for the awesome article Dave. It’s great to see some examples of high performance AJAX with ASP.NET.
One nice thing about the UpdatePanel and the ASP.NET AJAX framework is that it lets you get off the ground quickly, and show results to project stakeholders. This is especially important when the stakeholder has limited software development exprience and/or is unaware of the processes’ involved. We’ve all been there, if they can see it visually, it doesn’t exist ;).
As the project grows, if performance becomes critical, you can always remove the update panels and convert to the JSON/webservice implementations described here. In fact I would say having the option is one of the nicest things about the framework. If performance was the number one priority driving projects, we’d all still be writing in machine language or assembly.
Update panels give you “time to market”, which in today’s world is the most important driving force in software development. A good developer does not just write code a certain way because it is fast (fast to write, OR fast to run), they write the code because it is appropriate for the project requirements and scope.
Understanding the trade-offs is the key, and this article helps developers understand the trade-offs of using UpdatePanels. Just my 2 cents.
I definitely agree with that. I don’t recommend abandoning partial postbacks completely. I use them myself, when appropriate (and for prototyping).
I just think it’s very important for everyone to understand their drawbacks before running into said drawbacks. It’s easy to paint yourself into a corner with them, only to realize that fixing the problem will require major re-architecture.
but some times it is too difficult to render a component innerhtml via a web method (suppose that you want to rebind a combobox or grid ) what about that?
but i think that it is ideal for readonly or simple event controls (event implementable by javascript) such as text and captions.but is there any way to use this method for complex controls?what if we use control.RenderControl such as this?
I think this is what you’re looking for: http://encosia.com/2008/02/05/boost-aspnet-performance-with-deferred-content-loading/
Hi David
Very nice article!
I’ve been programming Windows Form for more almost 15 years now but I’m new to ASP.NET. We have been given the task to migrate a high complex windows app with a very heavy user interaction to Web app. The current windows app has a lot of grids to allow user modify different data sources, a lot of charts, reports etc. I totally understand your point about the importance to use carefully the UpdatePanels and that you should design your app properly. One of the big challenges we are facing though it’s how to achieve the same level of functionalities we have in the current windows app in the new web app we have to develop. Here is where my question comes. Do you know where I can find any good documentation about how to use these ASP.NET technologies “properly” when you have to build a Web app with a very heavy user interaction?
Usually, those reporting scenarios are a great place to implement user control rendering through a web service call. That’s how a lot of prominent sites implement their dashboards.
As long as the actual report data is read-only, using dropdown/textbox criteria to vary what’s displayed is easy.
However, if you have grids of data that need to be edited, I think that can be one of the few situations where UpdatePanels can make sense. Later, if you find that you need to optimize certain ones that are heavily used, you can always upgrade them with faster, client-side techniques for those.
If you need to rebind to drop down lists or a grid, then you really shouldn’t be using Ajax anyway, so you are stuck using fake ajax update panels.
On the other hand, it is extremely easy to actually build your OWN html objects for drop down lists, radio buttons, and even html tables, that are scriptable on the client side. This is the way that you HAD to do it in classic ASP and it really isn’t that hard to write a short loop to create lists and tables in html. It seems like so many programmers have forgotten how.
The sad thing is that so few of the builtin objects are really setup properly for CSS control or scripting. So I wrap some of these in my own user controls, and sometimes just roll my own, such as my own radio/check b