Monday, January 18, 2010

ASP.Net AJAX: Working with update panels

This post is for the people, who think that using update panels is nothing else but just add it to the page. This is not true !

I have noticed that a some developers are using update panels, as some kind of "metadata checkbox" - placing one update panel to wrap all the content of the page in its ContentTemplate. So in this post I will try to explain what exactly the UpdatePanels are for and how most from them.

First of all UpdatePanels are markers, which let you mark small, separate updateable areas on the page. Try to look at your page as a group of functionally independent areas. Decide which areas should be updated asynchronously and wrap those area code with UpdatePanel. Don't forget to include one <asp:ScriptManager runat="server" ... control on the page.

Job is done - you have the structure. But there is currently no difference from the page PV in what you had before (putting whole the content into one UpdatePanel) and what you currently got. Because by default The UpdateMode property of the UpdatePanel is set to Always, which makes the UpdatePanel to update its content on any postback. To fix this we just set the UpdateMode property of the needle UpdatePanel to Conditional. This makes the UpdatePanel to update its content by explicit requests (triggers, or just call to the Update() method of the UpdatePanel).

Now let's walk over a small example. Imagine you have a page with three UupdatePanels. All of them has some randomly generating content (random number for test). The first contains a button, which causes postback and has UpdateMode set to Always. The second also has UpdateMode set to always. The last UpdatePanel's UpdateMode is set to Conditional.

Now try to click the first button. This will update both update panels (which has UpdateMode set to Always). The third UpdatePanel whill keep it's content as was. Now click the third updatePanel's button. This will update all the three. Now add a handler to the first button's click event and call the Update() method of the third UpdatePanel). You will see that now after clicking the first button again all the updatePanels are being updated.

I have also attached a small code example (like the one described above). Hope it will help you to go deeper: http://www.sendspace.com/file/2lrs1w
Post a Comment