UpdatePanel - moving a control in the DOM causes such controls to be reset to their original state upon partial postback

708 views Asked by At

All controls involved are within the same update panel.

On the initial page load, I am moving controls in the DOM as such:

DIV_Child.Parent.Controls.Remove(DIV_Child) 'Remove from original parent'
DIV_NewParent.Controls.Add(DIV_Child)

On the initial page load, I am also manipulating these controls by adding styles.

DIV_Child.Style("position") = "absolute"
DIV_Child.style("background-color") = "black"
'etc.

When a partial postback occurs, DIV_Child goes back to its original state: unmoved and unstyled.

  • This problem only occurs for those controls that are moved within the DOM. If I remove those lines that move the controls, the controls maintain styling and DOM-positioning between partial postbacks.

How do I prevent moved-controls from losing their styles and new positions within the DOM upon partial postback?

1

There are 1 answers

3
sh1rts On BEST ANSWER

You need to use ContentTemplateContainer property to programmatically add or remove controls inside an UpdatePanel's ContentTemplate.

In your scenario you should add both containing DIV's (DIV_Child's parent and DIV_NewParent) as well as DIV_Child to the ContentTemplateContainer's Controls collection in PageLoad: -

    upd.ContentTemplateContainer.Controls.Add(DIV_OldParent);
    upd.ContentTemplateContainer.Controls.Add(DIV_NewParent);

    upd.ContentTemplateContainer.Controls.Add(DIV_Child);

The problem is occurring because your markup contains the div in its original position and style, and because it differs to what is submitted in a partial postback, the UpdatePanel is returning it as a change (simplified explanation).

Please give that a try.

I would usually recommend using an UpdatePanel for something quick and dirty, but for better performance instead use jQuery Ajax and a server-side HttpHandler. While this is (a bit) more work, it does give you better flexibility and you are guaranteed that nothing is going to interfere with the DOM section that is not inside an UpdatePanel.

I will concur that using UpdatePanels is a quicker development experience but they have a number of issues, not least of which is the fact that they post the ViewState back and forth with every partial postback, which is not very efficient.