ErnieStings
ErnieStings

Reputation: 6423

loading javascript file in ASP.NET for a single page

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

Upvotes: 1

Views: 1698

Answers (5)

Lazarus
Lazarus

Reputation: 43124

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.

Upvotes: 3

ADB
ADB

Reputation: 2329

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.

Upvotes: 1

cptScarlet
cptScarlet

Reputation: 6146

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

Upvotes: 4

Dan Diplo
Dan Diplo

Reputation: 25369

Can you just use the ClientScriptManager?

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

Upvotes: 1

Related Questions