views:

118

answers:

1

I have a User Control, named MyUpdateControl, that fires a startup script - its HTML is simply:

<div id="updatableArea"></div>

The startup script is added in the User Control's OnLoad():

string doUpdateScript = String.Format(
    "DoUpdate('{0}')",
    someValue);
this.Parent.Page.ClientScript.RegisterStartupScript(typeof(Page), "DoUpdateScript", doUpdateScript);

The MyUpdateControl User Control is sometimes contained within an Update Panel in another User Control:

<asp:UpdatePanel ID="myUpdatePanel" runat="server" >  
    <ContentTemplate>
        <UC1:MyUpdateControl ID="myUpdaterControl" runat="server" />
    </ContentTemplate>
</asp:UpdatePanel>

In those cases, the script is only fired when the page first loads. It never fires during an asynchronous postback. How can I ensure that it's also called during asynchronous postbacks?

A: 

You need to use the ScriptManager.RegisterStartupScript when registering a script within an UpdatePanel instead of ClientScript.RegisterStartupScript. There is an overload of this method that expects the control that is registering the client script block as its first parameter.

public class MyUpdateControl  : Control
{
    public MyUpdateControl()
    {         
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //..
        string doUpdateScript = String.Format(
            "DoUpdate('{0}')", someValue);
        ScriptManager.RegisterStartupScript(this, GetType(),
             "ServerControlScript", script, true);
        //..
    }
}

The example above uses a Custom Control, i realize you are using a User Control. The two implementations are very similar but i have included an example of this below for completeness.

public partial class MyUpdateControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {       
        //..
        string doUpdateScript = String.Format(
            "DoUpdate('{0}')", someValue);
        ScriptManager.RegisterStartupScript(this, GetType(),
             "ServerControlScript", script, true);
        //..
    }
}
Phaedrus