1

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

5 Answers 5

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Assuming they are using ASP.NET 3.5, this is the way I'd go.
3

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.

1 Comment

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.
1

Can you just use the ClientScriptManager?

if (!Page.ClientScript.IsClientScriptIncludeRegistered("MyKey"))
        {
            Page.ClientScript.RegisterClientScriptInclude("MyKey", "~/js/script.js");
        }

Comments

1

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.

Comments

0

How to embed javascript into a content page?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.