Easily refresh an UpdatePanel, using JavaScript
AJAX, ASP.NET, JavaScript, UI By Dave Ward. Updated March 19, 2008I’ve noticed a lot of discussion lately regarding methods to refresh an UpdatePanel via client script. This is very easy on the server side, of course. You can just call UpdatePanel.Update(). However, on the client side, the most common solutions I’ve been seeing just don’t feel right.
Many will advise you to use a hidden button control inside the UpdatePanel, manipulated via button.click(), to trigger a partial postback of the UpdatePanel. While it does work, I never have been able to get past the kludgey nature of that solution.
Finding a better way
To find a better solution, we’ll need a demonstration UpdatePanel to experiment with:
<asp:ScriptManager ID="ScriptManager1" runat="server" /> <div id="Container"> <asp:UpdatePanel runat="server" ID="UpdatePanel1" OnLoad="UpdatePanel1_Load"> <ContentTemplate> <asp:Label runat="server" ID="Label1" /> </ContentTemplate> </asp:UpdatePanel>
protected void UpdatePanel1_Load(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToString(); }
That’s a slightly modified version of the standard UpdatePanel DateTime example. Instead of the more commonly used Button_Click trigger, notice that the UpdatePanel’s OnLoad event is handled in code-behind.
Anytime UpdatePanel1 is loaded or reloaded in a postback, Label1 will be updated to reflect the current date and time.
Never fear, __doPostBack() is here
Luckily, there’s an easy method for triggering a postback targeted at the UpdatePanel: __doPostBack().
As long as the event target of a __doPostBack() call is an async trigger of an UpdatePanel, the ASP.NET AJAX framework will intercept the postback and fire a partial postback instead. For purposes of demonstration, I’m going to add that to the OnClick event of the container div:
<div id="Container" onclick="__doPostBack('UpdatePanel1', '');">
Now, clicking anywhere in the UpdatePanel will trigger a partial postback, targeting the UpdatePanel. Since partial postbacks follow the full page lifecycle, this will fire UpdatePanel1_Load and update the Label’s text.
A word on _doPostBack
You may have noticed that there is also an ASP.NET AJAX specific method of the PageRequestManager named _doPostBack. While it works much like __doPostBack, as long as the ASP.NET AJAX client framework is present, you should not call it directly.
The original __doPostBack method performs identically, but is more robust since it gracefully degrades to full postbacks when the ASP.NET AJAX framework isn’t available. It’s also unlikely that __doPostBack will disappear in future versions of ASP.NET, while it’s less assured that the ASP.NET AJAX framework will remain unchanged.
Similar posts
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.
7 Mentions Elsewhere
- SpinOneSolutions » Wrap AJAX Updates with Client Side Notifications
- 用__doPostBack在client端更新UpdatePanel | Horn Network
- Articles about __dopostback volume 2 « Article Directory
- image src not showing images
- Interactive Logic » Blog Archive » Easily refresh an UpdatePanel, using JavaScript [Encosia]
- ASP.NET and Ajax. All about update panels, web methods, page methods and jQuery » Coding Still
- ASP.NET and Ajax. About update panels, web methods, page methods and jQuery » Coding Still



It is a nice one to do.
Thanks. I was looking for something just like this!
So setting the ID of the UpdatePanel to “up1″ and then calling __doPostBack(‘up1′, ”) should do the trick? Doesn’t seem to work for me.
Oops, sorry.
My IDs were mismatched from trying to shorten parts of the code for better display here. Just make sure you’re calling __doPostBack() on the ID of an UpdatePanel that has an OnLoad handler set.
Did you ever figure out what was wrong?
It was just that I used “up1″ in one place and “UpdatePanel1″ in another, originally. Now that I edited them to be consistent in the example, it should work fine.
I don’t understand how this is less “kludgey?” It seems you’ve replaced the hidden button with a div. Not only that you may have introduced an unwanted side effect. If you have multiple updatepanels on the page and another updatepanel gets triggered to update your other updatepanel’s load function would run. It won’t update the screen, but if you have a session or viewstate value being changed in the load function that value will be changed. You can always test to see if the __EVENTTARGET is the correct updatepanel and only execute the code if it is, but that gets you nowhere if you’re trying for an elegant solution. It would be best if they just built in an updatepanel refresh from the client side.
The div and onclick are just for purposes of demonstration. People are often asking for a method to trigger the UpdatePanel through client script. Whatever their particular needs are, they obviously didn’t have an applicable button or they wouldn’t have asked to begin with. This is for them.
In real use, there would be no div onclick, nor the kludge button that others recommend. __doPostBack is a cleaner, more direct way.
There is no side effect introduced. If you have multiple UpdatePanels on the page, you would want to have those set to a Conditional UpdateMode, so there wouldn’t be any overlap. Only the panel targeted by __doPostBack’s __EVENTTARGET would execute its OnLoad.
Firstly, I think your site is tremendous and I have gone back through all your articles and find each one to be a little golden nugget. Great work. On to my question:
“There is no side effect introduced. If you have multiple UpdatePanels on the page, you would want to have those set to a Conditional UpdateMode, so there wouldn’t be any overlap.”
I have multiple update panels on the page, and when I try and update one using __dopostback(…, all the update panels’ OnLoad events get called. I have set their UpdateMode to conditional but it made no difference.
Am I missing something, or should this happen?
You’re not missing anything. I was wrong about that.
You can check Request["__EventTarget"] within the OnLoad events to determine which UpdatePanel was specified in __doPostBack() and react accordingly. Its value will be whatever is specified as the first parameter to __doPostBack().
The first argument to
is the UniqueID of a control, not the ID. If you have an update panel with ID=”UpdatePanel1″ nested in a control with ID=”Control1″ which is also an INamingContainer, the UpdatePanel would have an ID=”UpdatePanel1″, but a UniqueID=”Control1$UpdatePanel1″. You need the second – the UniqueID.
This approach to solve a common users request is not better of a fake button click. Use a double-underscored function and load an internal API variable like “EVENTTARGET” cannot be more clean than simulate a click. The last one is a complete no-no.
I think there is EVER an alternative to the use of __doPostBack, you had to delete it from your mind…
This is a my opinion.
Alessandro
OnLoad is going to run either way — on any postback. It’s just the usual load event of any control.
prm._doPostBack is the same as __doPostBack because __doPostBack is assigned to a delegate that invokes prm._doPostBack. Essentially, request manager overwrites the existing method.
But yes, __doPostBack has the advantage of working whether partial rendering is enabled or not. You definitely shouldn’t call prm._doPostBack — not only is there no reason to, but it’s private by the underscore convention (nothing is truly private in javascript of course, but the underscore basically means ‘dont touch this’). Ok, technically __doPostBack is private (*2* underscores, scarey!) too, but with how it’s used these days it may as well be public. Much safer bet.
Thanks for the clarification about the difference between the two methods. That’s good information.
I’m getting a javascript error ‘Object doesn’t support this method or property’
I have the below
Protected Sub UpdatePanel2_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdatePanel2.Unload
and I tried the Load but no joy
javascript
var prm = Sys.WebForms.PageRequestManager.getInstance();
//alert(prm); does create an Object
prm._dopostback(‘UpdatePanel2′,”);
any ideas
A couple things.
First, JavaScript is case sensitive. So, _dopostback isn’t the same thing as _doPostBack.
Second, use the double underscore method instead of the PageRequestManager’s. __doPostBack(‘UpdatePanel2, ”) should work. You’ll need to switch back to using the OnLoad handler for the UpdatePanel though.
This only work for regular web page..
When i apply on the content page, it will cause a a regular post back.
On more complex pages, try using __doPostBack(‘< %= UpdatePanel1.ClientID %>‘, ”) instead. If you use a DOM inspector to look at the rendered page, your UpdatePanel1′s ID is probably something more complex due to the nesting. Using .ClientID should resolve the correct rendered ID.
Good call Dave!
I wouldn’t have thought of that until the 11th hour.
In the more general case, where you need to be able to fall back to a full postback if no AJAX is loaded, you need the control’s UniqueID, not ClientID:
What happens is that, if the MS AJAX client scripts are loaded,
window.__doPostBackis replaced by a delegate function callingSys$WebForms$PageRequestManager$_doPostBack. If you open the MicrosoftAjaxWebForms.debug.js script file embedded as a resource in the MS AJAX assembly, you will see that UniqueIDs passed to the eventTarget paremeter are converted to ClientIDs. So, when using AJAX, it doesn’t matter if you specify Control.ClientID or Control.UniqueID. But the original __doPostBack() accepts only UniqueIDs to the eventTarget parameter. Otherwise, the page will postback, but the respective IPostBackEventHandler control will not catch the postback event.Thanks for this article – this was exactly what I was looking for.
I wish to add that apart from being ugly the button.click() method is not supported in Firefox according to my testing.
Unfortunatly __doPostBack(”,”); kills my IE 7 consistently. It´s a shame because it works so nicely in FireFox 2.x.
Do you have an example page I could take a look at? __doPostBack() definitely works in IE7 (otherwise ASP.NET wouldn’t), and I’ve tested this in it.
Ok, just to keep you updated: IE7 Developer Toolbar caused this issue. After deinstaling at IE stopped crashing.
Is anyone able to provide some real examples of why you need to refresh an update panel from the client side please.
Jason
I found it pretty handy when writing Display data updates in real-time with AJAX
Another excellent solution!!
Thanks Dave
i’m using this with a custom web control, it works fine but if i place it in an ajax update panel it fires a full postback,(i’m using onclick=’_DopostbackWithOptions…)
does anybody experience this?
I haven’t tried this technique with __DoPostBackWithOptions(). My advice would be to double check that the event target you specify is an async postback trigger.
Hi, I’m also using a WebControl, the __doPostBack works fine but the problem is… when I click a Button the UpdatePanel reloads first then executing the code behind the button. Is there a way to reverse the process? for instance execute the code behind the button first then firing the postback on the UpdatePanel? Thanks
Check the event target in your UpdatePanel’s OnLoad and only execute it if the event target is your UpdatePanel. Think of it like a !IsPostBack conditional for your UpdatePanel OnLoad.
Hi, Thanks for the quick reply, The problem of my application is that it doesn’t partial post back when I log on my application (Login.ascx)
I managed to solve my problem by adding a hidden field to my webcontrol and use the setTimeout() function in Javascript to post a partial update on my UpdatePanel ex. __doPostBack(”);
But using this script, is I have to depend onthe setTimeout function of javascript. Is there a better workarounds regarding this problem?
What you need to do is use the UpdatePanel’s PreRender event instead of the Load event. That will fire after the Button’s click event handler.
Sorry for the late response. I hope this helps.
Great solution, thanks! I used it for triggering a partial update on a page to execute a long lasting data call right after the page has been loaded. It works fine by registering a “__doPostBack(…” via ClientScript.RegisterStartupScript in the Page_Load handler. The only mandatory thing for it to work is to use an UpdatePanel.ClientID especially if your code is in a WebUser control or you use a Master Page.
That’s a good point about the ClientID. I omitted that to keep the example as simple as possible, but it’s definitely an issue on more complex pages.
Another option is to call __doPostBack(‘< %= UpdatePanel1.ClientID %>‘, ”)
Thank you very much for this. I really don’t like the concept of the hidden button method. It seems like it could be pretty problematic.
I was initially informed of this technique from a Joe Stagner video on the ASP.NET website, which mentions this article. The sample worked as I wanted, but as soon as I tried to implement this in my own site, I’d get a full postback. I figured out that the problem was with using a master page. But the comment from Alexander Turlov and yourself helped, and actually makes a lot of sense.
Thanks
My problem is refreshing an updatepanel that lies
inside a contentTemplate of a databound ajax accordion.
How can I access a specific updatepanel inside
that accordion (I cant get the ID of that panel)?
One way to do that is to write out a JavaScript array of ClientIDs to the client when you databind your accordion. Then, it’s easy to find the ClientID of the nth accordion’s UpdatePanel.
Could you be more specific (code)
I know how to do it in c# code behind
but Im not femiliar with somthing like ondatabound
in javascript
thanks in advance
Assuming you have a Repeater named “Repeater1″ with an UpdatePanel named “up” in each RepeaterItem, this would generate a JavaScript array of the ClientIDs of those UpdatePanels.
Then, if you wanted to refresh the nth UpdatePanel, you would use __doPostBack(RepeaterUpdatePanels[n], ”)
You should be able to do the same with an accordion. Just make sure to watch your page life cycle and do it after the accordion is databound.
Hi!, I hope someone can help me about this. Is it possible to have 3 UpdatePanels, the details are 1 (MainUpdatePanel) under that are two (UpdatePanel A & B). On UpdatePanel “A” I’ve put a webcontrol on it and has a button “Confirm” Now the question is it possible to the main update panel to be refreshed if we clicked the confirm button? thanks. so far no good here.
This probably isn’t the best place to find general help. The ASP.NET AJAX forum is a good place to ask questions.
That said, I believe your MainUpdatePanel should automatically update as a result of one of its children raising an event (unless you set its ChildrenAsTriggers property to false).
Hi Dave,
Sorry about that, but here’s another question about javascript. Is it possible to use Page.ClientScript.RegisterStartupScript() ? if how, Im using this but cannot trigger the dopostback. If I view source the page. I cannot see the script I’ve inserted via registerstartupscript
If you want to register it during a partial postback, use ScriptManager.RegisterStartupScript().
I have following code in aspx page. window.onload = loadUserControls;
var prm = Sys.WebForms.PageRequestManager.getInstance();
function loadUserControls()
{
__doPostBack(”, ”);
}
in code behing on unload event i have following code
protected void up1_unload(object sender, EventArgs e)
{
ph1.Controls.Clear();
Control cntrl = (UserControl) Page.LoadControl(“control1.ascx”);
if(cntrl != null)
ph1.Controls.Add(cntrl);
}
But it does not work. help/
Make sure your UpdatePanel’s declaration wires up your unload event handler, like:
Also, you need to target the UpdatePanel with your __doPostBack call. Change it to this:
Finally, you’ll want to enclose up1_unload’s code in an IsPostBack block of some sort. Otherwise, it will populate that PlaceHolder on initial load anyway, since UpdatePanel.Unload is going to run on every request.
I have another post that goes into some details about those page life cycle issues with UpdatePanels, that may help.
Dave,
i have exactly done what you have said in the post. Now i load the user control only if its postback which is raised by __doPostBack(”, ”);
when i put the break point, it goes inside the code like this:
BUT, I don’t see any thing in the placeholder. the only thing i have in control1.ascx user control is “this is test user control”. why is this. please help if possible.
Dave,
I am thinking that the reason I don’t see anything is because we are doing it on Unload event? when i put the same code in Load Event, It displays the content from the user control.
That’s probably it. I’d suggest putting it in the PreRender event, if that fits your page’s overall design.
I am not sure where to out it. its working on both Load and PreRender, where would you suggest?
why its not working on UnLoad?
My idea here is I want to load the page first and load the user controls so that user won’t see any blank screen since sometime user control might require some time to load.
would you have any idea.
Either Load or PreRender will probably work about the same for that. I typically use PreRender for something like that, so my code can respond to control events accordingly (since Load fires before control events like Click, Command, SelectedIndexChanged, etc).
Hi,
This technique is not working when we have master pages. It is doing a regular postback but not AJAX style postback. Is there any way to get this work. Any help is greatly appreciated.
- RJ
It will work in a master page scenario. Make sure that your target ID is correct. Master/content pages tend to leave your controls with interesting ClientIDs. Try using:
Substituting the ID of the UpdatePanel you want to target, for “UpdatePanel1″.
You saved my day. Appreciate your tip.
Thanks
Hello, has anyone done this:
MasterPage has a Web User Control called Cart.
Cart has a update panel.
The Product page uses the MasterPage and also has it’s own update panel.
After the user clicks a button on the product page (inside a update panel) how do I trigger and update on the Cart update panel?
You don’t need to use this technique to handle that. You can just call the cart update panel’s Update() method from your button’s event handler.
It’s a little more complicated than that when the update panel is on a different control and page.
You’d just need to expose your cart control’s UpdatePanel’s Update() method in a public method. Then, you should be able to call it from any scope you need.
If you want the cart control to update on every operation, you could put its data binding code in PreRender instead of Load. PreRender runs later than a button’s Click event handler, so the cart would automatically be updated after the button did its work.
I agree with RJ. I tried to implement the but still I get a full postback . Pls help..Tnx
See my reply to RJ’s comment.
Dave,
Nice and easy…Man, I was looking for this and thought it was going to be something dreadful. But it’s one line of code in my Javascript function.
My application, in case some are interested, is refreshing the UpdatePanel when the user resizes the browser window. I call the __doPostBack() from the Javascript function that handles the onresize event. It works great now!
Thanks,
Tony
I really like this method over the hidden field in the update panel. That being said is there a way to pass information to the server utilizing this method? I’ve got a list of links and depending on which is clicked I need to send a different value to the server. I’d like to just pass the information up as part of the postback, but don’t necessarily want to have to do it with a hidden field.
If you pass a parameter in the second argument of __doPostBack, it’s available on the server side in Request["__eventargument"].
So, say you refresh the UpdatePanel with __doPostBack(‘UpdatePanel1′, ‘Foo’) on the client side. In your UpdatePanel1_Load event handler, Request["__eventargument"] == “Foo”.
Awesome thanks for the help! Your idea is far and away the best method for causing the UpdatePanel to refresh from the client.
I just switched my hidden button solution to your approach. The hidden button worked fine in IE and Safari, but for some reson not in Firefox. Your approach now works fine in all browsers.
I can’t seem to get this working, experiencing the same as RJ and Barkowski, getting full postback. Looking at your reply I guess you are missing the ‘#>’ in your reply to RJ? (although this still doesn’t seem to help me) Any more ideas?
If __doPostBack causes a full postback, it’s always going to be the case that your UpdatePanel doesn’t have an AsyncPostBackTrigger matching the __EVENTTARGET that you’re specifying as the first argument to __doPostBack. Typically, that’s due to the ClientID of a control rendering different than how you expect.
A quick litmus test is to do a view source and make sure that’s not the case.
Also, if you’re using FireBug, you can call __doPostBack at the console to debug much faster than updating code and retesting.
Hi,
It seems the method does NOT work with GridView server cotnrol in .NET. On my page, I let a user click on an HTML Div element to trigger postback of an UpdatePanel. So, the wrapped Label control and Griview control contents should changed. But, only the Label.Text is changed and showed, but the GridView control is NOT seen.
Here is my code:
Hove to show GridView Customers
And code-behind:
protected DataTable GetCustomersData()
{
DataTable dt = new DataTable();
if (Session["CustomersData"] != null)
{
dt = (DataTable)Session["CustomersData"];
}
else
{
dt = DataBiz.GetCustomers();
Session["CustomersData"] = dt;
}
return dt;
}
///////////////////////////////////////////////////////////// JS client script triggers Ajax /////////////////
protected void UpdatePanel2_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
lblShowUpdatePanelID.Text = ((System.Web.UI.Control)(sender)).ClientID;
grvCustomers.DataSource = GetCustomersData();
grvCustomers.DataBind();
}
}
Any idea? Thank you in advance.
I can verify that it works against a GridView like that. I have production code working in roughly that same manner.
Have you tried setting a breakpoint in your UpdatePanel2_Load handler and verifying that GetCustomersData() is returning what you expect?
Also, double check for any later events that might be firing afterward and rebinding the GridView with empty data.
Dave,
I set a break point at GetCustomersData(), and I do see the data set return from that method.
By the way, what do you mean “Also, double check for any later events that might be firing afterward and rebinding the GridView with empty data.
“?
What events do I need to check after “protected void UpdatePanel2_Load(object sender, EventArgs e)”?
Thank you.
Since partial postbacks still run the full page life cycle, any event handler like Page_OnPreRender could be interfering with the final output.
Dave,
So, I have to move my code from event-handler
protected void UpdatePanel2_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
lblShowUpdatePanelID.Text = ((System.Web.UI.Control)(sender)).ClientID;
grvCustomers.DataSource = GetCustomersData();
grvCustomers.DataBind();
}
}
to event-handler
Page_OnPreRender() … ???
In that case event-handler “UpdatePanel2_Load()” is useless to fill data for my gridview???
Thank you for your help.
No, what I’m saying is that UpdatePanel2_Load isn’t the only event handler that will run when you __doPostBack(‘UpdatePanel2′, ”). If you have anything running in the normal page life cycle (like Page_Load, Page_PreRender, etc), it’s still going to execute in a partial postback, just like it would in a full postback.
This sounds like it’s a page life cycle issue, unrelated to what specifically is happening in UpdatePanel2_Load.
Without seeing the rest of your code, it’s a shot in the dark, but you might try using UpdatePanel2′s PreRender event instead of its Load event. That’s going to put your databinding farther down the life cycle, possibly after what’s causing your trouble now (though, you’d still want to solve the underlying issue, to avoid double data access/binding).
Dave,
I placed all of my codes on MS Ajax forum iste. For some reason, I cannot paste my HTML markup in here.
Thank for your looking at it.
Dave,
Thank you very much.
You would look at the codes over MS forum site. But never mind.
2 have 2 gridviews and 2 update panels on my page.
I found the problem and the codes work now. VS 2005 is totally SILENT about 2 different GridViews who use the same page changing event handler in HTML markup declarative part.
The problem is: in the HTMK markup page, for GridView grvCustomers2, I FORGOT to use its event OnPageIndexChanging as the SAME as event handler for GridView grvCustomers1.
I should have used a separate event handler for grvCustomers2.
I even dot not need to use Page_PreRender() because the problem does not come from there.
Dave this is a great solution.
However I have a small question. Is it possible to control the behavior of the update panels within a single page. In my case there is one update panel in my page and within the content template I’ve binded 4 user controls. In the main page there are 4 buttons where on the click of a button the update panel will be displaying one user control.(This is kind of a virtual tab control, where the 4 buttons are tabs and the Update panel is the content holder; please note i’m not allowed to use the ajax control toolkit which limits the use of the ajax tabcontrol)
However this has reduced the performance of the page. takes more time as all user controls are loaded each and every time the buttons are clicked.
Is there a way in which I can load the specific user control instead of all the user controls.
Basically I tried using 4 different update panels to hold the 4 different user controls. Still each time the page is posted back, all the update panels are updated resulting in reloading all the controls with regardless the need.
Can you please specify a way in which I can achieve this (i only want to load the specific update panel with a user control; not all user controls at once).
First, if these buttons can be server controls, it might make more sense to avoid __doPostBack. You could set those buttons as AsyncPostbackTriggers of the UpdatePanel and write code in their event handlers to load only the corresponding user control.
If you do need to use __doPostBack for other reasons, the key is to use the __eventargument parameter and check that on the server side. For example, call __doPostBack(‘UpdatePanel1′, ‘Tab1′) on the client side. Then in UpdatePanel1_Load, have a conditional or switch statement checking Request["__eventargument"] and loading the appropriate user control.
Hope that helps.
Thanks for the reply,
All the button are server controls and I’ve added the buttons as AsyncPostbackTriggers of the main UpdatePanel. Ofcourse I’m able to load only the corresponding user control.
However at the time of debugging using some break points I noticed that the code execution flow also goes through the load event of all the user controls.
Is this a nomal behavior (coz say if there are 4 tabs and I just want to access the very first tab; instead of the load event of that user control it also goes through the load event of rest of the three user controls. Finally ofcourse I get only the first tab selected and displayed in the page. I want to know if I can stop the load operation of the other three tabs until I make a selection of one of those tabs)
If I’ve understood any concept wrong please correct. (BTW: the page takes nearly 6-8 seconds to load. Although I use the update progress gif image, it won’t show up until the page is fully loaded. At the time of subsequent tab clicks the UpdateProgress can be seen in action).
Do you think this is something to do with Ajax, or something to do with HTTP requst. Coz I have no way of showing the end user something related to a UpdateProgress control for that initial 5-8 seconds.
waiting for your respose. Thanks in advance.
Previous comment was added by myself. Waiting for a reply.
Thanks
That is the expected behavior. Your entire page runs through its page life cycle, even in partial postbacks.
If I were you, I would only execute that code in the Button_Click handlers, and not in the controls’ OnLoad handlers. That way only the “tab” being requested would need to run through its initialization.
If you’d like me to take a look at the specific issue, email me a copy of the ASPX and code behind.
This was a great start to resolving some of the preformance problems that I have on the site that I working on. However, it does not seem to work in FireFox (2.0.0.9). How can this be used to convince FireFox to do an async postback.
In detail, I have a master page that has the ScriptManager on it. On a content page, is the containing div. I dynamically add a number of user controls that have the UpdatePanels on them. I am emitting the ControlID of the UpdatePanel to refresh back to the content page that is doing the __doPostBack on the UpdatePanel needing refreshing. Works prefect in IE, but FireFox does not do the update.
Thanks for your help.
David
Try emitting the UpdatePanel’s ClientID instead of ControlID.
I meant that I was emitting the ClientID, but typed ControlID, sorry.
I would look at the rendered source, copy that emitted ClientID, and then test it at the console in FireBug. Usually, a little trial and error at the FireBug console is the quickest way to find out what’s going on.
Hi there,
nice solution. I ran into problemns using an UpdatePanel set to UpdateMode=”Conditional” (need this cause i need ChildrenAsTriggers=”false”).
If set like this the script manager won’t do a partial postback for the update panel. Are there any solutions to this problem?
By the way, people may want to render the postback call through the ClientScriptManager:
ClientScript.GetPostBackEventReference(UpdatePanelXYZ,”")
Much nicer i think, and solves many master page related problems (notice that in the render proces it uses the panels name, not the client id).
__doPostBack will still trigger a partial postback when UpdateMode is conditional and ChildrenAsTriggers is false. However, when ChildrenAsTriggers is set to false, you’ll need to call .Update() in your UpdatePanel’s event handler to make the UpdatePanel actually render its updated contents.
Hope that helps.
I have tried all of these options and have not had success with any of these. I will illustrate the problem and the particular scenario I am trying to address.
We have a page containing a user control. The user control contains a ScriptManager, immediately followed by a different user control containing an UpdatePanel, and a second UpdatePanel that is filled with dynamically generated content. What we want to happen is the two UpdatePanels to be able to update independently as a result of a client-side JavaScript call.
The reason we are doing this is that we never want the page to have to be reloaded. The nested user control containing an UpdatePanel has to do a validation process of the users machine using an ActiveX control that requires at least one server post-back and occurs without user interaction. Then, the second UpdatePanel uses the results of that process from a client-side JavaScript. We want the process to execute once the first time the page loads and be able to be manually triggered it if necessary later in the process. The second UpdatePanel is executing steps of a workflow, sometimes requiring user interaction and sometimes not.
The solution should not be to add a control that will trigger a server side event because that is not practical for the steps that have no user interaction.
The problem is that no matter what we try we cannot get the two UpdatePanels to refresh without the other being refreshed also. Essentially we need to know what the caveats are for UpdatePanel so that we know where the two panels have to be hosted and where the ScriptManager needs to be hosted. Some of the methods that we have attempted and modifications to the structure that we have tried already are:
1. Adding EnablePartialRendering=?true? to the ScriptManager
2. Adding UpdateMode=?Conditional? to the UpdatePanels
3. Moving the ScriptManager to the hosting .aspx page
4. Moving the ScriptManager AND the nested user control to the hosting .aspx page
5. Using _doPostBack (from the PageRequestManager) vs. __doPostBack to trigger
6. Trying to manually filter out the post-backs based on __EVENTTARGET
7. Adding ChildrenAsTriggers=?true? in case our lack of triggers mattered
8. Using ID, ClientID and UpdatePanel.ClientID as the doPostBack argument
Obviously our scenario is not directly supported since we have to manually call the client-side post-back method, but can this be done and if so how?
Would greatly appreciate if you could provide any help with this.
Thanks
Kiran
If you want nested UpdatePaenels to operate independently, you need to set both to Conditional UpdateMode and set ChildrenAsTriggers to false on the outer UpdatePanel.
Is the ActiveX control what’s causing trouble? How does it trigger its postback? That’s probably going to be the tricky part.
Thanks for this post! I have been looking for a way to update an AJAX Accordion control within a Callback framework. This worked great (almost).
In my Accordion control I have some tags with JavaScript on-click methods. These are notbeing handled correctly b/c the page is not being updated with the html. Any ideas?
I’m not sure if I understand.
Are the onclick handlers not being re-wired after the refresh, or are they malfunctioning?
Thanks a lot!! I Found what i need!
Ah this really helped me out! I dont know if this was said before cause i dont have time to read all posts but if you use ctl00_ContentPlaceHolder1_UpdatePanel1 you can update an updatepanel in a content place holder (when using masterpage)
Dylan
Joining this discussion very late.
I am still getting full post backs when I call __doPostBack.
When you said that the page will run through it’s full life cycle do you mean that the Page_Load and Page_PreRender and so forth are still going to fire? If so, then I’m not sure I see the point. If they shouldn’t be firing then I still have a problem. I’m sure I’m passing the correct id in as a parameter to __doPostBack.
It seems like this was working until I added a second UpdatePanel to my page, although I never verified that.
Also, wasn’t clear about what you meant when you sad, “If __doPostBack causes a full postback, it’s always going to be the case that your UpdatePanel doesn’t have an AsyncPostBackTrigger matching the __EVENTTARGET that you’re specifying as the first argument to __doPostBack.” Were you just referring again to the ID vs ClientID problem that shows up with Master Pages?
Thanks so much.
That’s right.
Everything fires, just as if you triggered a full postback (Page_Load, Page_PreRender, etc). That’s how all partial postbacks work, whether triggered with __doPostBack or by interaction with a control (e.g. clicking a Button that’s an AsyncPostBackTrigger of the UpdatePanel).
To avoid that (and it’s worth avoiding when possible), you have to avoid UpdatePanels and partial postbacks. The better alternative is to use web service calls or page method calls instead.
Thanks for the info. That at least explains the problems I’m having.
I do have an unusual set of circumstances in that, exactly per your example, I need to trigger off the onclick event of a div tag and I need to to communicate with only one method on the server without going through the page life-cycle.
I suppose it’s a trade-off, by making AJAX very easy to use, Microsoft has severely limited it by forcing things like AsyncPostBackTrigger controls. It’s all fine if you need to create a popup calendar, but if you need to do something out of the mold it ends up being far more complicated than if you had just coded the solution yourself using Javascript and XmlHttpRequest. I could easily do what I’m trying to do that way, but I’ve been instructed to use the Microsoft framework.
I suppose I’ll have to use the original method that your method seeks to replace – create a hidden control trigger and initiate a click() event client-side. Yuck!
Again, thanks for the info and thanks for letting me vent a little.
Assume that you have an UpdatePanel1 and are handling its Load event (like in the example). If the Load event handler checks the __eventargument, you can call certain functionality from the client side:
Now, if I were to call __doPostBack(‘UpdatePanel1′, ‘UpdateTime’) on the client side, it would trigger a partial postback and update the label.
Is that basically what you’re after?
Yes, I think that will do it. Thanks!
I have a page that has 2 user controls and calls a javascript function that calls __doPostback() twice in succession. Both controls are in their own update panel. The page is does not update correctly and it appears that their is a lifecycle issue. If I add a javascript setTimeout on the second __doPostback, the page is updated correctly. Is there a better solution?
If you use two __doPostBacks in succession, it will trigger them both, but only the second one’s partial postback will complete (the first will be canceled immediately).
If you want to update the two controls sequentially, you could put the second __doPostBack in an EndRequest handler.
If you want to update them simultaneously, consider using UpdatePanel.Update() from the server side handler, after you’ve used __doPostBack to raise the postback.
I’m having an issue where i’m doing a async partial page postback yet the update panel is not rendering with the new data. The update panel contains a user control that has a grid view in it.
When debugging I follow the events (tried UpdatePanel.PreRender & Load events) all the way to the user control databinding the data to the grid view and I even put a label control to display the time. However the grid view and the time label are not updated in the rendering yet in debugger it shows that the label is being updated and that the grid view has new results. I’ve tried both the __doPostBack and asp:Button but both never reload the update panel with the new info. What am I missing?
It sounds like your Label and GridView aren’t inside the UpdatePanel(s) being refreshed in that request.
I’d suggest posting with code, on the ASP.NET forums.
Hi Dave,
This solution seems interesting but I can’t get it to work. I have posted the question on asp.net forum as well, but no answer yet.
I hope you can shed some light on my problem.
Here’s my scenario:
1. The Page has checkbox selection list and a submit button. The selected checkbox items are saved in session.
2. The UpdatePanel has a gridview with the button submit click event as the trigger.
On clicking the submit button, only the Grid gets populated – as expected.
But when the user navigates to the page again, the expected behavior is to load everything except the GridView. And then trigger the GridView load asynchronously
I am not able to do this successfully. I am leaning more towards the __doPostBack option rather than artificially causing the button click event. Reason being, I have to use partial page load patter in multiple pages across the app. And not all pages have buttons.
Any help is greatly appreciated! Here’s the link to my question:
http://forums.asp.net/t/1252524.aspx
thanks
hpdotnet
My Update Panel contain a Grid view containing alphabets A- Z. Also there is a datalist which gets binded on click of an alphabet in gridview(Record with that starting letter is displayed in datalist). I want the alphabet selected to be displayed in a different color. I have done that. But since the panel gets refreshed, the color appears and after few sec disappears(after completing databound). Plzz help me on this
Hi Dave,
I have a master page and a content page.On Page load in javascript i want to have 2 separate ajax calls to load master page as well as the content page.
Which would be the best option to do? My master page and content page ajax calls are no way related to each other.
If I use 2 update panels, both update panels send response back at the same time.
Usage of PageMethods is good but when there are controls like repeater, javascript coding for repeater would be very difficult.
Can you please suggest an approach to be taken here?
Regards,
Shilpa
Use UpdateMode Conditional, if you want only one panel to update at a time.
Hi Dave,
If i set Update Panel as “Conditional” then what would be the trigger for the Update Panels?
On Page load they would both get fired together.
You can check __EVENTTARGET to determine if a postback is targeted at a particular UpdatePanel (assuming you’re using __doPostBack to trigger it).
Good stuff, thanks. I especially appreciate the tip about Request[?__eventargument?] to pass info from the client side.
also you can use
Page.ClientScript.GetPostBackEventReference(Container, action, true)
it’s generate __doPostBack
Regards from Russia
Hi Dave,
I am new to the ‘UpdatePanel’. I would like to know your opinion on using UpdatePanel for the scenario as described below:
I have a page where the information is displayed on a repeater with 12 coumns. The first column of the repeater is a radio button. Users can select a radio button on a row and make that row editable. At this point the other rows on the repeater will be shown as labels. The editable row contains text as well as dropdowns. I used the repeater within UpdatePanel. When I clicked on a row it is taking almost a minute to bring the row to editable state. What can we do get a better performance?
Thanks,
Tom
See this post for an idea of why it’s slow: http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/
If you can eliminate ViewState and optimize your page lifecycle, you may be able to get that working acceptably fast with the UpdatePanel.
Otherwise, you’ll need to use a more client-centric method. This post gives an example of editing and saving data on the client side: http://encosia.com/2007/08/23/seamless-inline-text-editing-with-aspnet-ajax/
Those ideas can be adapted to work in your scenario without too much pain, but will probably require some fundamental changes. The performance is unbeatable though.
Hi Dave, Thanks for your idea and suggestion.
Thanks for this article. It solved my problem.
Listen to Dmitry above and use
Page.ClientScript.GetPostBackEventReference(Container, action, true)
don’t manually code __doPostback.
There isn’t much danger in coding __doPostBack. I suspect that will be around as long as WebForms are.
Hi Dave, my scenario may be slightly different, or at least I believe so since I am not able to trigger the update.
I have a calendar button on my main form aside a textbox (for a date). This opens another form that contains a .net calendar control. The OnChanged event then populates the original textbox back on the Main form and then closes the Calendar form. That is of course where I am trying to trigger the doPostBack, but is not doing so no matter how many different ways I have tried it.
For reference, I have followed your guidelines, I have atached an OnLoad event to my UpdatePanel on main form, it’s code will rebind the data in the datagrid within the UpdatePanel. My breakpoint in this function clearly indicates it never gets fired.
My attempts at thinking outside the box include creating a variable in the calendar page that referneces my Main page so I can access it’s functions and controls, but this yields controls cannot be accessed in this context type errors. Also have tried putting the rebinding code in the calendar page, and referencing Main page controls via the FindControl function. This does not error, and appears to work, but does not actually update the datagrid back on Main page.
Advice appreciated.
P.S. – In searching I have found links on the 2nd page method I am needing to do, but none of them explain or detail how this is actually done.
Thank you
Hi Dave,
Great Post. I came about this after it was mentioned and recomended by Joe Stagner in one of his excellent How To Videos on ASP.NET Ajax.
Once I saw your solution I got thinking about when you have a nested update panel in 1 or many INamingConatiners. I saw your solution where you compile an array of client IDs and then call via the index of its place in the array, but I was thinking about a away where I could reference the control in javascript in a more telling way.
My idea was to use javascripts useful dynamic function overloading or whatever its called. Basically you can supply a javascript function with as many arguments as you like without breaking it.
So I thought about a function where by the first argument is the control ID you want, and the following arguments starting with the highest parent down to the controls most direct parent.
function RaisePostBack() {
var controlID = “”;
if (arguments.length > 1) {
for (var i = arguments.length – 1; i > 0; i–) {
controlID += arguments[i] + “$”;
}
controlID += arguments[0];
}
else {
controlID += arguments[0];
}
__doPostBack(controlID, ”);
}
I am working on the fact that in INamingContainers the uniqueID is the controls complete parent heirarchy delimited with the dollar sign. So for example I tested this using a formview and an update panel inside.
RaisePostBack(“UpdatePanel1″, “FormView1″);
Notice that the method signature is different to how I am executing it. So in essecence I could then nested it further
FormView1
–FormView2
—-UpdatePanel
RaisePostBack(“UpdatePanel1″, “FormView1″,”FormView2″);
The Function will generate the unique ID for example based on the above as:
FormView1$FormView2$UpdatePanel1
Anyway thanks for the idea that lead me to this little function which for a project I am on, is just what the doctor ordered.
Cheers,
Andrew
I can’t seem to be able to get an async postback to work when using a master page?
I call __doPostBack(”,”)
in the masterpage with the UpdatePanel1 in a contentpage and then in the masterpage’s pageload()
IsInAsyncPostBack is always false?
Can you get this to work with a master page?
Sorry the code did not show up correctly. I call..
and don’t get async post back with master page but I do with just a webform?
If you’re adding this to your page declaratively in the ASPX, you need to use an ASP expression to inject the UpdatePanel’s actual ClientID. Like this, for example:
That will work in both a Master Page and regular WebForm.
edit: Ignore the rel=”nofollow”. WordPress is very aggressive about the spam prevention!
Maybe I’m missing something easy, but when I set;
the rendered page shows:
In case that doesn’t render correctly, in the first block the less than and greater than symbols are correct. In the second block, they are replaced with ampersand lt/gt instead of being resolved server side with the update panel’s ID.
Thoughts?
-Rick
Try putting it in a javascript function. This works for me.
function DoUpdate() { __doPostBack('',''); }Then call it like this
Rick, it sounds like you might be adding that on the server side, instead of declaratively in the ASPX. Is that the case?
I created a similar method to update the UpdatePanel through javascript and wrapped it in a ExtenderControl…
Take a look at it here.
Thanks. Excellent stuff! Just what I was after!
Hi Dave,
Your post looks gr8 but can you help me in this scenario
I have an UserControl in a aspx page and the user control has 5 updatepanels
There is a hyperlink in each of the updatepanel, onclick of this hyperlink i will popup a new page using Thickbox.
In the popup page i enter some data and when submit it i need to populate those values in the gridview placed in the parent page and close the child window.
so while submitting the child page i call the following javascript
Page.ClientScript.RegisterStartupScript(GetType(String), “closeThickBox”, “self.parent.RemoveModalAndUpdate(‘UpdatePanel1′);”, True)
This calls the RemoveModalAndUpdate JS function placed in the Master page.
But for me the whole page is getting postback.
Can you please tell me where i’m going wrong?
Thanks in advance
Hello. I was reading all the stuff coz i got problems refreshing grieviews on UpdatePanels with js.
I finally use the “normal” code __doPostBack(”, ”); grapped within a function, called in a return null.
The only thing i was missing is filling again the GridView… I did put the “DataBind()” in UpdatePanel’s Load Event but it didnt work. Im using Store procedures with ExecuteNonQuery function instead of datatables or other kind of datasources. So i just put again the SqlDataAdapter and fill my dataset and then databind my gridview and thats all, it works.
I hope it was usefull for somebody.
Thanks.
Ups, i didnt format the __doPostBack well…
“__doPostBack(”, ”);”.
sorry
How come I can get this working OK normally, as described above, but.. when I put the above example into a user controla and then drop that user control into a webpart zone (so to create a webpart) it only shows my result after the update panel is cycled for a second time. Using basic example of click button (ok/cancel) result is alert(‘hello world’) propagated by a scriptmanager.regstartupscr(‘Call my clientside JavaScr function’) placed in the code behind of the updatepanel_Load.
So. I click button, says:
(click OK or Cancel), I click OK. Nothing happens. I then click the button again which causes an async psotback and immediatly shows me hello world and also (after I click OK on that) shows me the origional confirmation prompt.
However, as I said above if I run the example in a normal webform (nor Ucl in WebPartZone) its fine and works as it should, showing me the ‘Hello World’ immediatly after I click OK on the confirm prompt.
Any ideas why this is happening? (I made an example of this so I can post the code if you wish).
Many Thanks.
James.
If you can generate the URL in code (not declaratively), you could use this syntax to generate your postback hyperlink
Page.ClientScript.GetPostBackClientHyperlink(WebControl, [optional parameter])
and then retrieve the info in page_load using
If Page.IsPostBack AndAlso Request.Item(Page.postEventSourceID) = WebControl.ClientID Then
Dim param As object = Request.Item(Page.postEventArgumentID)
[do update]
exit sub
end if
This is pretty cool, I was also dabbling with a hidden button and looking for something like this. But I still have a problem – I want my updatePanel to update conditionally on the arguments I pass to doPostBack – how do I read them back in UpdatePanel_Load?
thanks!
protected void UpdatePanel_PreRender(object sender, EventArgs e)
{
this.UpdatePanel1.Update();
this.GridView1.DataBind();
}
Great article. There is one VERY important note for those reading if not already mentioned; I spent 2 days trying to figure this out: If your code that uses JavaScript to fire an UpdatePanel is in an ASP.NET Content page you need to raise the event with the following code:
__doPostBack(”, ”);
You MUST use ‘UniqueID’ and NOT ‘ClientID’. ClientID will actually seem to work, you will get no errors, and the partial postback will even fire, but the wired up button click event in the server side code will NEVER fire (Page_Load will fire and the cycle will proceed, but the wired up event is never ran). Once I changed it to button.UniqueID, the server side event code finnaly was ran!!
I had this pinned down because I had the exact same code in (2) simple pages: one that was a regular .aspx page and one that used Master pages. The regular page would hit the server side wired up click event just fine, but the exact same code in the Content page version would not run. That is until I changed to use the ‘UniqueID’ of the control.
I hope this saves others time in the future.
My last post has some of the JS stripped. It should have ‘ ‘ (without spaces) as the 1st parameter in the doPostBack call.
I don’t know how to post the answer: button.UniqueID is the parameter, but wrap it with the server tags as displayed at the beginning of the page.
atconway: thankyou thankyou thankyou thankyou thankyou x infinity squared
And thanks to Encosia for being google friendly
This is great! Thank you. Just what I needed to get the update panel to refresh without a button.
It works fine for one update panel, but doesn’t seem to work with multiple update panels or multiple user controls with update panels.
Can’t figure out how to load simultaneously (!!!) multiple update panels, or multiple user control that contain update panels.
Seems like a dead end to me if I want to load simultaneously multiple user control with update panels after the static content of the page is loaded.
Trying to achieve the same functionality as on http://www.pageflakes.com/ for example still using the update panels and server side asp.net controls.
You’re right that this won’t work for multiple simultaneous updates. Only one partial postback may occur at any given time, with newer ones canceling older ones. So, UpdatePanels aren’t well suited to the scenario you’re describing.
Take a look at this technique instead: http://encosia.com/2008/02/05/boost-aspnet-performance-with-deferred-content-loading/
Thanks Dave,
The link you provided is a little different approach, which has it’s own pluses and minuses.
Dynamically loaded or dynamically rendered controls is something else.
I still want to try to make it work with update panels and __doPostBack(). Although I can put __doPostBack() in pageLoad function to initiate a postback for each update panel or control with update panel, there is another problem, that I encountered and you have already posted here: http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/
So, pageLoad doesn’t seem like a working method to solve that problem. But, maybe, through some manipulations with Sys.Application.add_init(function()) it would be possible to achieve the result?
It’s a little weird that if you have a button in each update panel or control with update panel, and you click that button everythere, when in fact, the loading of the panels would be simultaneous.
So, it is possible, just curious if I can find a way to initiate such postback for all these update panels (or controls with update panels) when the page loads.
Anyways, thanks for you blog, it’s extremely useful.
The problem is that only one partial postback may ever be running at any given time. No matter what you do to trigger them on the client-side, you won’t be able to load multiple individual blocks simultaneously. Web services (or plain HTTP GETs, like jQuery’s $.load()) are the only way to achieve the effect that you see on Pageflakes.
That’s the conclusion I came to as well. Just wanted to be sure that I am not mistaken about it. Well… javascript + web services seems to be the only way. And it’s probably the best way, very optimized, json instead of soap xml, and of course no viewstate, no postbacks. But… in this case you have to forget about asp.net controls at all and develop your own javascript controls for UI (or use some library).
Thanks Dave for confirming this issue with me!
Hi
Have implemented this solution on a panel which contains a mixture of client buttons (anchor tags) and asp controls (linkbuttons).
All is fine except that the last line of code executed when an asp linkbutton is clicked is a response.redirect(“otherpage.aspx”).
Unfortunately this line is completely ignored. Doesn’t cause any error its just ignored ie. new page is not loaded.
Anyone know a way out this
Wing Yip
Great article… I have been looking for a way to force automatic ajax postbacks for some time now.
This works like a charm.
If anyone should be interested I simply put a line of javascript code in the pages that should auto-postback:
This executes ‘__doPostBack’ for my update panel ‘MainUpdatePanel’ every 15 minutes, so I can save a draft of what the user has done so far.
This is a great idea – yet there is a problem since the callback assigned to the OnLoad has no meaning, i.e. when defining an OnLoad it will be called for any asynchronous callback –
You can see it happening in the following case, when clicking one button trigger both pannels:
One way to handle conditionally triggering updates using this __doPostBack() method is to test __EVENTTARGET on the server-side.
If you call __doPostBack(‘UpdatePanel1′, ”) on the client-side, __EVENTTARGET will be “UpdatePanel1″ in ol1 and ol2. Test that it is “UpdatePanel1″ in ol1 and “UpdatePanel2″ in ol2.
This didn’t work for me – couldn’t click and get a refresh/postback. Even tried turning it into a span, and adding runat=”server” – didn’t work either of those ways, either. I’m trying to use a button to fill a DataTable, do a “foreach” loop and have a field from each record appear (very fast) through a label control in an UpdatePanel. Right now it will only refresh at the end, even though I have an UpdatePanel1.Update() in the loop. Not sure why it doesn’t refresh the label. Any help?
-Tom
hi!
Thanks for this wonderful post. I am tring to use it with an Accordion. I am unable to do so, kindly help correct my syntax
Thanks
that’s still a little kludgey in my eyes, but a lot better than the other approaches. thanks!
This is great…thank you! I’m using this approach in a page with UpdatePanel with UpdateMode conditional. I also have an UpdateProgress indicator that shows when update takes more than 500 ms. I’m using PageMethods to check for updates to the page(instead of ASP.NET AJAX timer because it postbacks the whole page). If page needs to be updated, then I call __doPostback for the UpdatePanel. In the UpdatePanel load on server side, I then rebind the data. It works fine. But often posting back this way takes a LONG time, UpdateProgress shows the spinning gif and I get timeout error in PageEndrequest. I increased the AsyncPostbackTimeout, but it didn’t help. As a workaround, when I get timeout, I reload the location in the browser but it is not a good user experience.
Thanks in advance for any tips and pointers!
Regards
Great, thx a lot.
Navin, this is the same situation that i’ve described (see above), so take a look at Dave’s response from December 20, this will help you – or doit in my way, see below:
protected void UpdatePanel_OnLoad (object sender, EventArgs e)
{
var upnl = sender as UpdatePanel;
if (upnl != null)
{
switch (upnl.ClientID)
{
case “UpdatePanel1″:
// do somthing…
break;
case “UpdatePanel2″:
// do somthing…
break;
}
}
}
All the best.
Dude, your code doesn’t work for the reasons you think it does.
Update panel’s Load event fires during postbacks of any type so calling __dopostback with “UpdatePanel” is redundant.
If you call __doPostBack() without specifying an AsyncPostBackTrigger as the first parameter (the EventTarget), you’ll get a full postback instead of an async postback. The UpdatePanel itself is always an implicit AsyncPostBackTrigger, even if the UpdatePanel’s UpdateMode is “Conditional” and ChildredAsTriggers is “false”, which is why I recommend using it as the EventTarget.
Hi Dave, really great article.
Could I bind a grid in an update panel and after finish the postback call another update to fill a word tag user control located in another update panel? The word tag depends on the grid results and we don´t want that the grid wait for the word tag user control.
Tks a lot,
- Juliano
(Leme / Brazil)
Unless the word tag control is very slow, you probably won’t notice much difference by doing that. If the word tag control is purely read-only (i.e. it doesn’t need to respond to postbacks itself), which it sounds like it may be, you might consider doing something like this instead: http://encosia.com/2008/02/05/boost-aspnet-performance-with-deferred-content-loading/
thx so much its very good for me :)) thx
Hi Dave – the asyncronous postback only happens for me when using the html textbox onfocus event. What if I wanted to use an asp:TextBox like:
<asp:TextBox ID="txtbox1" runat="server" MaxLength="10" TabIndex="1" CssClass="small" onfocus="__doPostBack('’, ’122′); return false;” />
I had this code working great, and it did exactly what I wanted it to do. However…
it’s now giving me an error, saying: “Sys.ArgumentTypeException: Object of type ‘String’ cannot be converted to type ‘Array’. Parameter name: updatePanelsToUpdate”
Seems that it doesn’t know what to do with the first parameter, as it wants it an array form rather than the string that is identical to your code. I’m guessing that something else on the page is making it grumpy, but I’m pretty sure the markup is exactly how it was when I had it working. Any ideas on this at all?
Developing WebSite With Master Page
I have navigation menus at the master page. I am using Html anchor tag for navigation. I want that on Clicking the Menu i:e Anchor Tag Only the Content Page is Post Back not Whole Page i:e MAster Page Content + Content Page.
Wow – thank you. I have been working with the hidden button solution which gets more complicated with validators, and after seeing your example, I just streamlined the whole thing. Thanks a ton for sharing this!
I have an ancillary question that I hope isn’t too far off topic:
I have a situation where I’m trying make the Rows of a GridView clickable. I tried the “traditional” way with Page.ClientScript.GetPostBackEventReference(this, e.Row.RowIndex.ToString())
That works but unfortunately a full page postback occurs. I’d much prefer to do just a partial page postback. I was able to successfully implement Dave’s “__doPostBack…” approach but was unable to figure out how to pass a parameter (namely, the RowIndex) back.
Might anyone have any ideas?
Would there be a reason my textboxes located outside (after) the updatepanel wouldn’t have their value stored in the viewstate?
From my updatepanel_Load event (called from javascript), the textboxes’ values are all empty strings.
The other controls higher up on the page seem to be retaining their values.
Have you double checked that they don’t have their EnableViewState property set to false, either declaratively in the ASPX markup or imperatively from the code behind? The other thing to watch out for is that controls which were dynamically added to the page need to be recreated early in the life cycle on every PostBack in order to be correctly re-populated with ViewState-driven data.
Got your reply, David (however I don’t see it on the site yet). Thanks for your time!
Yes, the controls in question do have EnableViewState set to true (and is not overridden in code). Nothing on this page is created dynamically, but I do understand the issues if that was the case.
I’m stumped. We’re not talking about 1 or 2 controls here. Its EVERYTHING after the updatepanel (like 10 or more controls). :-(
Any other thoughts? Thanks again.
I’ve never run into anything like that. It might be best if you post as much of your code as possible on Stack Overflow and get more eyeballs looking at it.
I’ve run into some problems using this solution, I have a Scriptmanager and an UpdatePanel in my UserControl.
In my javascript I try to do a __doPostBack(”, ”);
This however refreshes my entire page.
Any ideas?
It’s important that the first parameter to
__doPostBack()is the ClientID of a control which is an AsyncPostBackTrigger. That can be the UpdatePanel itself (as in this example), any of its AsyncPostBackTriggers, or any control inside the UpdatePanel if ChildrenAsTriggers is true (deafult: true).Found the solution myself I missed some lines in my web.config. Don’t know why they weren’t there but it’s fixed now.
My __doPostBack() contained the clientID, for some reason my post got edited when submitting it.
Thanks for your help.
Super helpful, thanks.
The key sentence for me was “As long as the event target of a __doPostBack() call is an async trigger of an UpdatePanel, the ASP.NET AJAX framework will intercept the postback”
meaning I had to add this before the post back was async ..
.. the reason i am overriding the clientside on click handler for something called a ‘button’ is a long story to do with Custom Button class and having to do some stupidity involving MS CMS before the postback begins.
I tried using all the examples above, I can’t get it to partial post.
Help Please
Opps, i modified it to be runnable by you, but forgot to add
Place above:
I dont want the list to have to post back, just the project editor control.
What am I doing wrong?
Try using just
__doPostBack('udpEditor', '');instead of the PageRequestManager method. I loaded your page up in VS and was able to get an asynchronous postback by executing that command from my browser’s console.Thanks, I must have misunderstood, now I just need to figure a way to pass the selected key.
Thank you.
NM, I figured it out.
Thanks for all the help.
<pre lang="csharp"
protected void udpEditor_Onload(object sender, EventArgs e)
{
if (IsPostBack == true)
{
int intTaskID = clsStrings.SafeInteger(Request.Form["__EVENTARGUMENT"]);
LoadTask(intTaskID);
}
}
-- Master at WinForms, Learning WebForms and not liking what I see.
hi
can we pass a parameter to behind code to update panel with specified range of data in this way.
from 2 days i’m working on refreshing update panel issue, thanku so much, its woking like charm
Great article, its very useful
We can also submit our .net related article link on http://www.dotnettechy.com to increase traffic.
I was using this technique until recently as I discovered it does have a maybe dangerous side-effect. For some reason this technique will execute a DataBind on any other UpdatePanels on the page even if they have a Conditional UpdateMode and ChildrenAsTriggers as false. So, if you have any kind of decalarative DataSource on the page it would most likely rebing that and make unnecessary calls to the database.
I’d say actually emulating a click from a trigger button is a safer bet.
Ezequiel
It sounds like what you’re discovering there is more related to WebForms’ approach to generating the page than using
__doPostBack. No matter how you trigger a postback, any code in OnLoad handlers is going to run. If you have code that only needs to run on the first pageview and not on subsequent postbacks, it’s important to wrap that code in anif (!IsPostBack)conditional so that it only executes on that first run through the page life cycle.Thanks so much, been a battle with this one
thak you Dave Ward
this saved me a lot time!
Can I do something like that after an Jquery ajax succeed in a lightbox?
I want to refresh the content of the repeater in an updatepanel which is in a lightbox. Can I do that as well?
My code is something like that.
$.ajax({
…the usual
success:funciton(){
//refresh the update panel content here.
//can i do the __doPostBack here?
}
});
Encosia is simply the best reference ever on this subject.
Thanks again to the person behind all this.
So simple. So obvious. Thank you.
Once I had an experience of not functioning the async postback because of not getting the correct CliendID of update panel.
So I used the ClientIDMode=”Static” to ensure it gets the proper id.
I found one problem with this solution. I’ve got a gridview inside an update panel. I have one column that calls some javascript when clicked that will call the postback just fine and everything updates well
But if you ALSO have a command button inside a template field in that gridview, it renders that command button useless.
Inside that ONLOAD method I tell the gridview to refresh. When you click a command button , now instead of the RowCommand method firing, the ONLOAD method fires FIRST, which KILLS the rowcommand event. So the rowcommand never fires.
Basically, it looks like if you’re going to use javascript to update an update panel from the inside, anything else that updates what’s in the update panel ALSO has to use javascript,