最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

loading javascript file in ASP.NET for a single page - Stack Overflow

programmeradmin0浏览0评论

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 acplish this?

thanks in advance

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 acplish this?

thanks in advance

Share Improve this question asked Aug 19, 2009 at 12:17 ErnieStingsErnieStings 6,42319 gold badges48 silver badges55 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 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

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.

Can you just use the ClientScriptManager?

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

There are a couple of ways to acplish 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.

How to embed javascript into a content page?

发布评论

评论列表(0)

  1. 暂无评论