1

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

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

<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>
4

1 回答 1

1

答案就在这里,所以请奖励作者,但要将其调整为 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>
于 2012-06-30T00:08:35.007 回答