Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

February 9, 2010

ASP.NET: UpdatePanel and Master Pages

Filed under: ASP.NET,C#,VB.NET @ 7:21 pm

I had an ASP.NET page with two UpdatePanel controls. I wanted to handle the page refresh differently depending on whether the user clicked on the button in the first UpdatePanel or whether the click was on the button in the second UpdatePanel.

After a little time with Bing, I found the IsInAsyncPostBack and AsyncPostBackSourceElementId properties of the ScriptManager and thought I was good to go. But no. The page had no ScriptManager control because the ScriptManager was on the master page.

I had put the ScriptManager on the master page because almost every one of my pages needs some AJAX control or another. I didn’t want to move it onto every page.

So back to Bing for more research. I found several solutions for getting the ScriptManager from the master page, one of which required about 60 lines of code.

Then I found this one:

In C#:

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsPostBack)
    {
        ScriptManager sm = ScriptManager.GetCurrent(this.Page);
        if (sm != null && sm.IsInAsyncPostBack)
        {
            if (sm.AsyncPostBackSourceElementID ==
                           AddButton.UniqueID)
            {
                //  Do whatever
            }
            else
            {
                //  Do the other thing
            }
        }
    }
    else
    {
        // Setup the page text and populate lists. 
    }

}

In VB:

Protected Sub Page_Load(ByVal sender As Object, _
                    ByVal e As System.EventArgs) Handles Me.Load
    If IsPostBack Then
        Dim sm As ScriptManager = ScriptManager.GetCurrent(Me.Page)
        If sm IsNot Nothing AndAlso sm.IsInAsyncPostBack Then
            If sm.AsyncPostBackSourceElementID = _
                           AddButton.UniqueID Then
            ‘  Do whatever
            Else
            ‘  Do the other thing
            End If 
        End If
    Else
        ‘ Setup the page text and populate lists.
    End If

End Sub

This code uses the ScriptManager GetCurrent static method to find the ScriptManager associated with the page. It then uses that instance to check the IsInAsyncPostBack property. The AsyncPostBackSourceElementId provides the unique Id of the element on the page that generated the post back.

Use this technique whenever you need to obtain the ScriptManager from the master page.

Enjoy!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2023 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs