【问题标题】:Creating a sub-title with a Master Page and ContentPlaceHolder使用母版页和 ContentPlaceHolder 创建子标题
【发布时间】:2013-07-16 16:47:58
【问题描述】:

我的网站有几个页面,我希望页面的标题是:

Foo - 1st Page
Foo - 2nd Page
Foo - 3rd Page

我使用以下代码创建了一个母版页:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Foo.master.cs" Inherits="Foo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Foo - <asp:ContentPlaceHolder ID="SubTitle" runat="server"></asp:ContentPlaceHolder></title>
</head>
<body>
    <asp:ContentPlaceHolder ID="MainContent" runat="server">
    </asp:ContentPlaceHolder>
</body>
</html>

然后每个页面看起来像这样:

<%@ Page Language="C#" MasterPageFile="~/Foo.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="SubTitle" runat="server">1st Page</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <a href="Page2.aspx">Page 2</a>
</asp:Content>

当我在浏览器中加载页面时,我希望标题为Foo - 1st Page,但它只是1st Page。

html源码是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
  1st Page
</title></head>
<body>

<a href="Page2.aspx">Page 2</a>

</body>
</html>

我做错了什么?

【问题讨论】:

  • 生成的 标签是什么? (无论如何,这对我来说是占位符的不寻常使用。)我想知道是否有更好的解决方案是在代码隐藏中设置页面的标题属性。
  • @ThatBlairGuy - 我将 html 源代码添加到我的问题中。 Visual Studio 的 Master Page 模板在 MasterPage 的标题标记中有一个名为 title 的 ContentPlaceHolder。我只是在它前面添加了Foo - 文本,并将其重命名为SubTitle。

标签: asp.net master-pages contentplaceholder


【解决方案1】:

您不想从head 中删除runat="server";它会产生其他问题。

使用以下方法,这是 Visual Studio 2012 中 ASP.Net Web 窗体应用程序中的默认方法。

<!-- Master Page -->
<head runat="server">
    <title>Foo - <%: Page.Title %></title>
</head>

<!-- Content Page/xxx.aspx -->
<%@ Page Title="Home Page" ...>

【讨论】:

  • 优秀。谢谢你。出于我的目的,缺少runat="server" 不会导致问题(这只是一小部分测试页面,head 中没有其他内容)但我接受了您的建议,因为它使代码更简单。跨度>
【解决方案2】:

原来这个问题已经被问过了:ASP.NET: Having common Page title in master page with each page adding page-specific title?

在阅读了那里的答案后,我发现从母版页的 head 元素中删除 runat="server" 可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2016-06-01
    • 2013-10-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多