Thursday, August 6, 2015

Prevent full post back, when using update panels and AjaxControlToolkit with dynamically loading controls

Update panels which support us in every ASP.NET development are really useful, but when we added AjaxControlToolkit reference to the project and if we are loading dynamic controls that cause a post-back then update panel's behavior is not working as we expected. It should be a compatible issue.

But how to over come this. Let's look at a simple example.

I'm creating a project that's have a repeater controller and it has drop-downs inside with some values and those drop-downs will post-back to the server once the selected index changed (for no reason).
And to show the update panels are working I'm using a <img> and with java-script I will load a Image to that, and then when drop-downs selection change image should not be refreshed.

Here is the full html and the coding to bind the repeater that i'm using. And <img> with file input is inside a update-panel and it's update mode is set to conditional while in the repeater's update panel mode is set to default(to always).

If you look at the reference list AjaxControlToolkit is not added.Now this works perfectly, you can change the drop down index and it will cause a partial post back but still the image will be there.

image is loaded and drop-downs are in default selection.
drop-down selection changed and still the image is there because update panels are working fine

Problems comes when you adding the AjaxControlToolkit  as a reference to the project, suddenly update panels will not work and when you change the drop-down selection, full page will be refreshed and image will be gone.
(No need to use AjaxControlToolkit in your page if you add it to the solution then it will not work)

So what actually went wrong, this is a compatible issue, what happening is those drop downs are not registered into the update panel, cause they are dynamically adding.

How to overcome this :
There are two ways we can overcome this,

  1. When repeater item bound you can find the item and then you can register it as a async post back control, which is the hard way.(ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(dropdown1);)
  2. The easy way is to change your page's property client id mode to "AutoID". Then all the dynamic controls will assign an id when its's creating and registered with the update-panel.

So that's it, hope you will find this help full one day. Cheers and  Happy Coding.

No comments:

Post a Comment