mike44
mike44

Reputation: 812

ASP.NET adding js file on page load

I need to add specific js files to the page. On Page_Load, I'm trying this:

ClientScript.RegisterClientScriptInclude("MyTab", HttpRuntime.AppDomainAppPath + "\\scripts\\" + tabName);

It doesn't working.

Upvotes: 0

Views: 1002

Answers (3)

Peter
Peter

Reputation: 14098

Make sure you're not using "MyTab" anywhere else to register scripts. It's a key for the script.

Also HttpRuntime.AppDomainAppPath will return the physical path, which makes me think it could return for example C:\Program Files\... which won't work for people visiting the site.

Maybe try:

ClientScript.RegisterClientScriptInclude("MyTab", Page.ResolveClientUrl("~\\scripts\\" + tabName));

Upvotes: 0

hutchonoid
hutchonoid

Reputation: 33306

You can simply do this without the need to load it in the code-behind:

 <asp:ScriptManager ID="sm" runat="server">
   <Scripts>
     <asp:ScriptReference Path="./script.js" />
   </Scripts>
</asp:ScriptManager> 

If you want to add or change the script file at runtime, just leave the ScriptManager in your mark-up and access it like this:

   ScriptManager sm = ScriptManager.GetCurrent(Page);
   if (Smgr != null) 
   {
     ScriptReference sr = new ScriptReference();
     sr.Path = "~/Scripts/Script.js";
     sm.Scripts.Add(sr);
   }

Upvotes: 0

Sanjeev Rai
Sanjeev Rai

Reputation: 6982

You can try this solution that will always work. use:

Page.Header.Controls.Add(new LiteralControl("<script type='text/javascript' src='script.js'></script>"));

Upvotes: 2

Related Questions