Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure js is included in ascx file?

So the problem is the following :

i do have own user control. which has some javascript file in script tag included like this

<script type="text/javascript" src="../somefile.js" ></script>

or some javascript code directly on the ascx page. everything works if i place this control somewhere in aspx markup. but if i add this control to the page dynamically to some UpdatePanel place holder on postback (this is logic i can not alter), control renders itself and then i get js error message, which says that functions which are placed in somefile.js are not defined/are null. Why is this happening ? Is there anyway to force js including in this case.

sorry for being not enough specific but the code amount is huge and i was not able to provide a simplified example with the same error,.

The script is included but somehow the functions are not defined. I'm novice to js, so is it possible that just the script is included but not executed, so the functions are not declared ???

The interesting is that if on some page my custom control is declared in aspx. The adding some more instances dynamically causes no problem.

like image 928
danyloid Avatar asked Feb 17 '11 03:02

danyloid


2 Answers

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

if (!Page.ClientScript.IsClientScriptIncludeRegistered("keyName"))
    Page.ClientScript.RegisterClientScriptInclude("keyName",
        Page.ResolveUrl("~/Scripts/MyJavaScript.js"));
like image 55
Jonathan Wood Avatar answered Oct 05 '22 08:10

Jonathan Wood


How about including it in ScriptManager.Scripts like this?

<asp:ScriptManager runat="server" ID="scriptManager1" EnablePageMethods="true">
        <Scripts>
            <asp:ScriptReference Path="~/somefile.js" />
        </Scripts>
</asp:ScriptManager>

Edit:

From ascx you could do something like this (OnPreRender would be where I would try this):

ScriptManager.GetCurrent(Page).Scripts.Add(new ScriptReference("~/somefile.js"));

Alternatively, you could try

 ScriptManager.GetCurrent(Page).RegisterClientScriptInclude(
            this,
            typeof(Page),
            "UniqueScriptKey",
            ResolveClientUrl("~/somefile.js"));

Reference link

like image 37
Bala R Avatar answered Oct 05 '22 10:10

Bala R