views:

75

answers:

2

Is it possible to add javascript reference dynamically from code behind aspx.cs?

Like this:

private void AddScriptReference(string path)
{
   //Add reference to <head></head>
}

Should result in a script reference being added to the head of the page, like this:

<html>
   <head>
      <script type="text/javascript" src="path-to-script.js"></script>
   </head>
</html>

Is this possible?

+1  A: 

You can use the ASP.NET Ajax ScriptManager to do so.

Add it to your masterpage, and use ScriptManager.RegisterClientScriptInclude from your codebehind.

Jan Jongboom
Thank you, I should have known this :P
Martin
+1  A: 

For those who want to know the syntax, here it is:

Master Page:

<asp:ScriptManager ID="ScriptManager" EnablePageMethods="true" runat="server"></asp:ScriptManager>

Code behind:

ScriptReference sr = new ScriptReference("path-to-js.js");
ScriptManager sm = (ScriptManager)this.Master.FindControl("ScriptManager");
sm.Scripts.Add(sr);

Or:

ScriptManager.RegisterClientScriptInclude(this.Page, GetType(), "UniqueID", "path-to-js.js");

But none of these solutions actually add the script to the head of the page..

Martin