views:

150

answers:

5

I'm using ASP.NET with a master page containing a script manager. I want to add a javascript file to only one page, but all pages inherit from the master. What is the proper way to accomplish this?

thanks in advance

+2  A: 

In the Master Page add a content container in the HEAD section, in your page put the Javascript tag inside the instance of that container.

EDIT - for d03boy

On MasterPage:

<head runat="server">
  <asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>

On ContentPage:

<asp:Content ID="LocalHeadContent" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="javascript" \>
</asp:Content>

For any content page that doesn't have something to include in the page header there's no need to even create the Content tag.

Lazarus
This is really the best solution? What if he has 500 pages attached to that Master page and only 1 of them needs the javascript.
Joe Philllips
See edit above, hopefully that'll make it clear.
Lazarus
+1  A: 

Can you just use the ClientScriptManager?

if (!Page.ClientScript.IsClientScriptIncludeRegistered("MyKey"))
     {
      Page.ClientScript.RegisterClientScriptInclude("MyKey", "~/js/script.js");
     }
Dan Diplo
+1 That's the way I prefer.
Canavar
not the best one, IMHO the ScriptManagerProxy is easier way.
Kamarey
+4  A: 

Add a script manager proxy to the page you wish to add the javascript to and then add the javascript reference using the script manager proxy

cptScarlet
Assuming they are using ASP.NET 3.5, this is the way I'd go.
Zhaph - Ben Duguid
+1  A: 

There are a couple of ways to accomplish what you are looking for.

1- put a content place holder in the section of your master page

<head runat="server">
    <asp:ContentPlaceHolder runat="server" ID="JavascriptPlaceHolder">
    </asp:ContentPlaceHolder>
</head>

and in the specific page you want to add a javascript file add:

<asp:Content ID="Content2" ContentPlaceHolderID="JavascriptPlaceHolder" Runat="Server">
    <script type="text/javascript" src="myfile.js" ></script>
</asp:Content>

2- When you are not using Update Panels, use the ClientScript:

Page.ClientScript.RegisterClientScriptInclude("MyKey", "/myfile.js");

3- When using Update Panel and partial page rendering, use the ScriptManager object to register your javascript: (For a script that should be available for the onload event or at least be available when an update panel refreshes)

string javascript_string = "function myAlert(){ alert('me'); }";
ScriptManager.RegisterStartupScript(this, typeof(string), "MyKey", javascript_string, false);

Use the content place holder where you can, then use either other technique when you can't.

ADB