Update: this fix is now on CodePlex: CodePlex. Get the latest version from there.
The scenario is pretty straightforward: a ListBox or DropDownList or any control that renders as a Select html element with a few thousand entries or more causes an asynchronous UpdatePanel update to become incredibly slow on Internet Explorer and reasonably slow on FireFox, keeping the CPU to 100% during this time. Why is that?
Delving into the UpdatePanel inner workings one can see that the actual update is done through an _updatePanel Javascript function. It contains three major parts: it runs all dispose scripts for the update panel, then it executes _destroyTree(element) and then sets element.innerHTML to whatever content it contains. Amazingly enough, the slow part comes from the _destroyTree function. It recursively takes all html elements in an UpdatePanel div and tries to dispose them, their associated controls and their associated behaviours. I don't know why it takes so long with select elements, all I can tell you is that childNodes contains all the options of a select and thus the script tries to dispose every one of them, but it is mostly an IE DOM issue.
What is the solution? Enter the ScriptManager.RegisterDispose method. It registers dispose Javascript scripts for any control during UpdatePanel refresh or delete. Remember the first part of _updatePanel? So if you add a script that clears all the useless options of the select on dispose, you get instantaneous update!
First attempt: I used select.options.length=0;. I realized that on Internet Explorer it took just as much to clear the options as it took to dispose them in the _destroyTree function. The only way I could make it work instantly is with select.parentNode.removeChild(select). Of course, that means that the actual selection would be lost, so something more complicated was needed if I wanted to preserve the selection in the ListBox.
Second attempt: I would dynamically create another select, with the same id and name as the target select element, but then I would populate it only with the selected options from the target, then use replaceChild to make the switch. This worked fine, but I wanted something a little better, because I would have the same issue trying to dynamically create a select with a few thousand items.
Third attempt: I would dynamically create a hidden input with the same id and name as the target select, then I would set its value to the comma separated list of the values of the selected options in the target select element. That should have solved all problems, but somehow it didn't. When selecting 10000 items and updating the UpdatePanel, it took about 5 seconds to replace the select with the hidden field, but then it took minutes again to recreate the updatePanel!
Here is the piece of code that fixes most of the issues so far:
/// <summary>
/// Use it in Page_Load.
/// lbTest is a ListBox with 10000 items
/// updMain is the UpdatePanel in which it resides
/// </summary>
private void RegisterScript()
{
string script =
string.Format(@"
var select=document.getElementById('{0}');
if (select) {{
// first attempt
//select.parentNode.removeChild(select);
// second attempt
// var stub=document.createElement('select');
// stub.id=select.id;
// for (var i=0; i<select.options.length; i++)
// if (select.options[i].selected) {{
// var op=new Option(select.options[i].text,select.options[i].value);
// op.selected=true;
// stub.options[stub.options.length]=op;
// }}
// select.parentNode.replaceChild(stub,select);
// third attempt
var stub=document.createElement('input');
stub.type='hidden';
stub.id=select.id;
stub.name=select.name;
stub._behaviors=select._behaviors;
var val=new Array();
for (var i=0; i<select.options.length; i++)
if (select.options[i].selected) {{
val[val.length]=select.options[i].value;
}}
stub.value=val.join(',');
select.parentNode.replaceChild(stub,select);
}};",
lbTest.ClientID);
ScriptManager sm = ScriptManager.GetCurrent(this);
if (sm != null) sm.RegisterDispose(lbTest, script);
}
What made the whole thing be still slow was the initialization of the page after the UpdatePanel updated. It goes all the way to the WebForms.js file embedded in the System.Web.dll (NOT System.Web.Extensions.dll), so part of the .NET framework. What it does it take all the elements of the html form (for selects it takes all selected options) and adds them to the list of postbacked controls within the WebForm_InitCallback javascript function.
The code looks like this:
if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += name + "=" + WebForm_EncodeCallback(value) + "&";
}
That is funny enough, because __theFormPostCollection is only used to simulate a postback by adding a hidden input for each of the collection's items to a xmlRequestFrame (just like my code above) in the function WebForm_DoCallback which in turn is called only in the GetCallbackEventReference(string target, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync) method of the ClientScriptManager which in turn is only used in rarely used scenarios with the own mechanism of javascript callbacks of GridViews, DetailViews and TreeViews.
And that is it!! The incredible delay in this javascript code comes from a useless piece of code! The whole WebForm_InitCallback function is useless most of the time!
So I added this little bit of code to the RegisterScript method and it all went marvelously fast: 10 seconds for 10000 selected items.
string script = @"WebForm_InitCallback=function() {};";
ScriptManager.RegisterStartupScript(this, GetType(), "removeWebForm_InitCallback", script, true);
And that is it! Problem solved.
36
comments
36 comments:
Wow, thanks a lot! I've searching for both a reason and a solution for this unusual problem, and you've shown me both! What a marvelous post!
I have tried your solution and it worked fine. However once I add any extender to the dropdownlist such as ListSearchExtender it gave an error "Sys.InvalidOperationException: Two component with the same id 'ListSearchExtender1' can't be added to the application". Could you tell me how to deal with this error? Thanks a lot.
As far as I see, that error is thrown by Application.addComponent when it finds in the array _components a component with the same id as the one to be added.
If indeed my code is to blame, then possibly Ajax attaches to elements an array of extenders that it clears onsubmit, then it reattaches them.
I will investigate.
I was right. The array in question is called _behaviors (with American spelling). I've updated the code with one line, the one with _behaviors in it :)
Thank you for pointing out the problem.
Thank you so much for this quick fix. You literally saved my life.
Would this work if I have mulltiple ddls that I need to apply it against and if so - how?
Well, you would have to take the last piece of code, the one that disables the old style CallBack, and put it in a separate method that you execute once.
Then add a parameter to RegisterScript (maybe rename it to something else) that would be the ListBox that you want processed and use that ListBox instead of lbTest.
And for the end, load the CallBackDisable method then RegisterScript for each of the listboxes you need fixed in the Page_Load event.
Dear Sir,
Thank you so much, it works for me.
when i call registerscript for both the dropdownlist, i am getting error 'Select.options.length' is null or not an object
but works fine if i have only one dropdownlist,
The method in the post is a sample only. If you want it to work for more dropdownlists you need to change it to accept lbTest as a parameter.
Yes i changed lptest to receive it as an parameter and then first called callbackdisposble and then called registerscript to accept the dropdownlist as an parameter, still i see it takes lot of time, can you please let me know how to fix this
Thanks
How would you do this using vb?
So, here is the entire method, with a listbox as a parameter. Use it in Page_Load:
/// <summary>
/// Use it in Page_Load.
/// lb is any ListBox
/// </summary>
private void RegisterScript(ListBox lb)
{
string script = string.Format(@"
var select=$get('{0}');
if (select) {{
var stub=document.createElement('input');
stub.type='hidden';
stub.id=select.id;
stub.name=select.name;
stub._behaviors=select._behaviors;
var val=new Array();
for (var i=0; i<select.options.length; i++)
if (select.options[i].selected) {{
val[val.length]=select.options[i].value;
}}
stub.value=val.join(',');
select.parentNode.replaceChild(stub,select);
}};
",lb.ClientID);
ScriptManager sm = ScriptManager.GetCurrent(this);
if (sm != null) sm.RegisterDispose(lb, script);
string script = @"WebForm_InitCallback=function() {};";
ScriptManager.RegisterStartupScript(this, GetType(), "removeWebForm_InitCallback", script, true);
}
Great solution. Do you have a vb equivalent?
I've got the vb equivalent if anyone's interested. I just can't seem to post it to this blog. It keeps saying Your HTML cannot be accepted.
Thank you. Thank you. Thank you!
I implemented the solution via VB. I registered the element swap part of the script to the RegisterDispose event. I am collecting the selected ListBox items via the button's OnClientClick event so that I can process and display them before the PostBack.
You're welcome! Someone making use of what I write fuels this blog.
I was able to implement your solution on a standalone page. I am trying to implement it on some dropdown list controls that are in the Edit- and InsertItemTemplates of a FormView which is in a Content Page. The ScriptManager is in the Master page. The scripts appear to be firing (I stuck alerts in them) but the performance doesn't improve. Do you have any suggestions that I could check?
Thank you and Merry Christmas.
Well, you would have to tell me more and I would have to have more time to investigate [Hint! :)].
Try profiling the javascript, try it in FireFox and Chrome and see if the javascript or the rendering are at fault, etc.
This looks exactly like the problem I'm having with my dropdown lists, they have around 1000 rows, due to business requirements I cant make them any smaller. On initial load, the performance is ok, but whenever the user chooses an item in the list, the refresh takes much longer.
Sorry for the stupid question, but your sample code is for a listbox, would anything need to be changed to get it to work for a ASP.net ddl ?
I have posted a solution that works for both here:
http://forums.asp.net/p/1360932/2832582.aspx#2832582
Thanks again, Siderite!
Thanks very much Siderite!
Well, the ListBox is a glorified DropDownList. It should work for both, I don't see why not. You are welcome.
Thank you for your excellent research! I'm impressed!!
Don't usually post in these forums, but this solution worked a treat and saved me a lot of hassle.
I use it for a number of Drop Down Lists I have on my page and it works by simply passing the DDL to the RegisterScript function as Siderite mentioned in the comments.
Thanks Siderite!
hi, can this solution applied to Ajaxtoolkit cascadingdropdown as well?
The AjaxControlToolkit cascading control uses web services to get the data and populate the dropdown lists. This fix of mine works exclusively on UpdatePanel postbacks.
Perfect, solved a very irritating problem for me too.
This is marvellous. It helped as to solve a critical issue
gr8 post!!!1
Thanks for this Siderite.
I'll be honest and say I have no idea how it fixes the problem but I simply copied your code, used a C# to VB converter, had to change 1 minor part of it and it works like a charm.
Lovely.
many thanks for that solutions man!
could you tell me how do you investigate the root cause? I mean what tools or debugger you used to identify the problem? many thanks!
Well, I hardly remember it now, but one of the major things one must do in order to identify ASP.Net problems is to use Reflector and the File Dissassembler addon to get all the sources for the .Net libraries, especially, in ASP.Net's case System.Web and System.Web.Extensions. You also get the javascript files that are used, so you can browse through them.
One other hint is to use a debugger. Register a debugger; keyword as a submit statement, then debug with whatever debugger works best. For example, at the time, I had installed Microsoft's Script debugger, which, even if it was pretty basic, succesfully found the js source at the debug point as opposed to Visual Studio.
So, the bottom line is that you need to think like a computer :)
Thank you, thank you, thank you. This problem was driving me crazy. Your fix worked like a charm.
Great post - works well - thanks for your work.
One problem though is that it only works if the large list item is loaded in the PageLoad event.
If the list box is loaded via an update panel, then the problem returns, but only for the first post back - then it is fixed again.
I'll try and decipher the code a bit more, but if anyone has solved that issue I would love to know more
Cheers
Problem Solved!
This solution only implements itself if the list box contains more than 50 items (which is fine for most cases)
If you are like me and want to start with an empty list box, then edit ListControlUpdatePanelFixAdapter.csand change the MinItemCount property to return -1 (instead of 50). Then rebuild the solution and grab the new output dll.
Now this solution always implements itself and no more slow listboxes
Post a Comment