Thursday, July 2, 2009

Which UpdatePanel caused the Post?

Now that is a question! And the answer tool me nearly a day to discover. (OK, all of you that know the answer, stop snickering. I'm just learning the ASP.NET AJAX model)

After many dead ends, here is the key to finding what UpdatePanel caused the Post:
ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID

This returns the actual element ID that forced the Post. How does this help? Well, any post that originated in a UpdatePanel would be from a child control. So, if you walk up the control tree and find a UpdatePanel, you will have the UpdatePanel that caused the Post.

private UpdatePanel GetUpdatePanelThatCausedPostback()
{
var c = Page.FindControl(ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID);

while (c != null && !(c is UpdatePanel)) { c = c.Parent; }

if (c != null) return (c as UpdatePanel);
else return null;
}


Here we get the control that actually fired the Post and then we walk up the control tree, one by one, until we are either past the top (null) or we have found an UpdatePanel.

Then we simply either return the newly found UpdatePaenl or we return null.

No comments: