简体   繁体   中英

Execute javascript in an ascx.cs usercontrol

I'm dynamically adding controls to my ascx.cs usercontrol and therefore I also need to dynamically execute javascript code from my ascx.cs usercontrol.

I'm executing my javascript using:

Page.ClientScript.RegisterStartupScript(typeof(Page), "reOpen", "<script type='text/javascript'> reOpenClick(); </script>")

This is my javascript in the ascx file

<%@ Register Assembly="obout_Window_NET" Namespace="OboutInc.Window" TagPrefix="obout" %>

<obout:Window runat="server" ID="ow_dialog" Width="200" Height="50"
    Title="Open" IsModal="true" ShowCloseButton="true"
    StyleFolder="~/Styles/obout/window/grandgray" VisibleOnLoad="false">    
   .
   .
   .
   .
</obout:Window>

<script type="text/javascript">

    function reOpenClick() {
        ow_dialog.setTitle("Open");
        ow_dialog.screenCenter();
        ow_dialog.Open();
    }

</script>

When running the code as usual I'm getting the error ReferenceError: ow_dialog is not defined . But when typing reOpenClick() into the web browser's console everything runs fine.

Why am I getting the ReferenceError: ow_dialog is not defined when typing in the function in the console works fine?

Add script tags to the markup

<script type="text/javascript">
   // place your javascript here
</script>


<script type="text/javascript" href="path to js file" />

or

In the load event of your control, do something like this:

if (!Page.ClientScript.IsClientScriptIncludeRegistered("keyName"))
    Page.ClientScript.RegisterClientScriptInclude("keyName",
        Page.ResolveUrl("~/Scripts/jsfile.js"));

If the user control is in an UpdatePanel and/or its Visible attribute is set to false by default, you will get "Object expected" error because simply your script is not loaded when the page loads and the function you are calling is non-existent.

Workaround for this is to use style="display:none" instead of Visible="false" for your user control in the main page.

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