简体   繁体   中英

How to load javascript function from an dynamicall added control?

The Master page got a ScriptManager.

Then i got a Control with a ScriptManagerProxy and an UpdatePanel.

Inside the UpdatePanel there I dynamically add a Control (also containing a ScriptManagerProxy) and from that control I need to run some JavaScript code.

DynamicControl.ascx:

<script type="text/javascript">
    function doSomething() {
        alert(1);
    }
</script>

DynamicControl.ascx.cs:

public void Page_Load(object sender, EventArgs e)
{
...
ScriptManager.RegisterStartupScript(
this.Page, this.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);

My problem is that the function "doSomething()" is never called and i dont know why. :S Edit: It is called but not directly when i add the control.

If I do code like this, there will be an alertwindow:

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

Ok I think i need to add some more information:

The control is dynamical added inside a jQuery Dialog. And I found out that the javacode is first executed after i close and then open the dialog. Some kind of event is triggered so that the code is executed there i think. Is it possible to force this event? so the scripts are executet directly when the control is added ?

placeHolder.Controls.Add(dynamicReportControl);

This c# code doesn't execute the javascript tag immediately ?

Please try something like this

ScriptManager.RegisterStartupScript(
this.UpdatePanel1, this.UpdatePanel1.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);

Where UpdatePanel1 is your UpdatePanel

Try setting the addScriptTags argument to true, and remove the script declaration from your code.

Is that code only supposed to run on every request? If so, why not just add this code to the ASCX:

window.onload = doSomething();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM