是否可以多次重复一个占位符的内容?

时间:2012-06-29 13:57:04

标签: asp.net-mvc-2 master-pages

是否可以在母版页的多个位置使用ContentPlaceHolder的内容?

例如,我经常想做类似的事情:

<html>
 <head>
  <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
  <link rel="Stylesheet" href="../../Content/Corporate.css" />
 </head>
 <body>
  <div id="header">
   <h1>I'd like to reuse the TitleContent ContentPlaceHolder content here?</h1>
  </div>
  <div id="content">
   <asp:ContentPlaceHolder ID="MainContent" runat="server" />
  </div>
  <div id="footer">
   &copy; 2012 Acme corp.
  </div>
 </body>
</html>

1 个答案:

答案 0 :(得分:1)

答案是here,所以请奖励作者,但要将其调整为MVC,这是您需要做的:

首先:定义您自己的母版页类(Site.Master):

<%@ Master Language="C#" Inherits="MyProject.Views.Shared.MyMasterPage" %>

第二名:班级内容:

public class MyMasterPage : ViewMasterPage
{
    protected override void RenderChildren(HtmlTextWriter writer)
    {
        var mainPlaceHolder = FindControl("TitleContent");
        var doublePlaceHolder = FindControl("TitleContentDuplicated");

        var sb = new StringBuilder();

        using (var sw = new StringWriter(sb))
        using (var tw = new HtmlTextWriter(sw))
        {
            mainPlaceHolder.RenderControl(tw);
        }

        var lc = new LiteralControl(sb.ToString());
        doublePlaceHolder.Controls.Add(lc);

        base.RenderChildren(writer);
    }
}

第三:然后您可以使用:

<title>
    <asp:ContentPlaceHolder ID="TitleContent" runat="server" />
    <asp:ContentPlaceHolder ID="TitleContentDuplicated" runat="server" />
</title>