Handleman
Handleman

Reputation: 754

Using LoadControl for a usercontrol with javascript in it

This might fall into the "I think you're doing it wrong" category, but I have a usercontrol that has javascript in it and I want to dynamically load it in an update panel. This is so the initial page load footprint is small, but if the user makes the request the control is loaded (nothing unusual).

I'm finding my javascript is not being executed when the control is loaded. Is there some magic to make the javascript execute, or will it never happen because the browser won't re-parse the loaded html for tags?

My User Control

<div>hello</div>
<script type="text/javascript" >
alert('hello');
</script>

Page ascx

<asp:Button OnClick="LoadTheControl" runat="server">Click to Load</asp:Button>
<asp:UpdatePanel ID="myUPanel" runat="server">
    <asp:PlaceHolder ID="WantControlHere" runat="server" />
    <Triggers>
          <asp:AsyncPostBackTrigger ControlID="LoadTheControl" />
    </Triggers>
</asp:UpdatePanel>

Page cs

protected void LoadTheControl(object sender, EventArgs e)
{
    MyControl control = (MyControl)LoadControl("~/MyControl.ascx");
    control.ID = Guid.NewGuid().ToString();
    WantControlHere.Controls.Add(control);
}

Firebug shows me all the code of my control is there, but the javascript it is not executed.

Please point out my stupidity.

Upvotes: 1

Views: 1629

Answers (1)

Waqas
Waqas

Reputation: 6802

I think in order to execute a javascript once your control is loaded, you have to register it using ScriptManager.RegisterStartupScript method.

Inside the Page_Load method of your control register the script your want to execute like this:

ScriptManager.RegisterStartupScript(this, this.GetType(), "sub", "alert('me');", true);

Upvotes: 2

Related Questions