7

我知道我可以通过这种方式(在代码后面)以编程方式访问使用母版页的页面的 head 部分:

只是一个例子(我想插入脚本和样式等):

this.Header.Title = "I just set the page's title";

是否有一种简单的方法可以在 aspx 文件本身中以声明方式执行此操作?

有时插入客户端脚本样式声明或指向外部资源的链接会很方便。

4

4 回答 4

22

您可以通过在 中使用内容区域来做到这一点,其方式与在页面head中的方式完全相同body。例如,在您的母版页中:

<head>
    <link type="text/css" rel="stylesheet" href="/styles/common1.css" />
    <script type="text/javascript" src="/scripts/common1.js"></script>
    <asp:contentplaceholder id="ExtraStylesAndScripts" runat="server" />
</head>

然后在页面本身就像:

<asp:content contentplaceholderid="ExtraStylesAndScripts" runat="server">    
    <link type="text/css" rel="stylesheet" href="/styles/extra1.css" />
    <link type="text/css" rel="stylesheet" href="/styles/extra2.css" />
    <script type="text/javascript" src="/scripts/extra1.js"></script>
    <script type="text/javascript" src="/scripts/extra2.js"></script>
</asp:content>
于 2009-02-20T09:38:48.917 回答
6

对于样式表,您可以使用:

HtmlLink cssRef = new HtmlLink();
cssRef.Href = "addins/main.css";
cssRef.Attributes["rel"] = "stylesheet";
cssRef.Attributes["type"] = "text/css";
Page.Header.Controls.Add(cssRef);

对于元标签

HtmlMeta metaTag = new HtmlMeta();
metaTag.Name = "author";
metaTag.Content = "ScarletGarden";
Page.Header.Controls.Add(metaTag);

但是没有办法将外部脚本文件添加到标题元素。

您可以通过以下方式添加内部正文元素:

if (!ClientScript.IsClientScriptIncludeRegistered("myExternalScript"))
{
   ClientScript.RegisterClientScriptInclude("myExternalScript", "js/myJSFile.js");
}

希望这可以帮助 !

于 2009-02-20T08:48:24.343 回答
2

您可以在内容页面声明中声明页面标题。

<%@ Title="Page Title" Page Language="C#" AutoEventWireup="true" CodeFile="Subpage.aspx.cs" Inherits="Subpage" MasterPageFile="~/MasterPage.master" %>
于 2009-02-20T09:00:17.153 回答
0

我没试过这个。
但是您可以将 HEAD 元素放在 html 中,并使用 asp 样式标记中的封闭字符串。

例如 <%=myTitle%>

于 2009-02-20T08:40:07.047 回答