【发布时间】:2011-05-23 11:04:44
【问题描述】:
我想从母版页后面的代码编辑 ContentPlaceHolder 的内容,请帮助我,您可以假设任何母版页带有任何内容占位符。
所有答案都会得到尊重。
【问题讨论】:
-
我宁愿说它反对主内容。你能解释一下为什么需要那个吗?
标签: asp.net master-pages
我想从母版页后面的代码编辑 ContentPlaceHolder 的内容,请帮助我,您可以假设任何母版页带有任何内容占位符。
所有答案都会得到尊重。
【问题讨论】:
标签: asp.net master-pages
如果内容更改是微不足道的和装饰性的,请考虑客户端操作,例如jQuery.
否则,您可以在 ContentPlaceHolder 的 Controls 集合上使用 FindControl(),但这很麻烦而且很混乱。
更简洁的解决方案是利用Polymorphism。调用页面可从 MasterPage 的 Page 属性获得。
所以:如果你有这样的界面:
public interface IContentInjectable
{
Literal ExposedLiteral { get; }
}
你的页面模板是这样实现的:
<%@ Page Language="C#" MasterPageFile="~/MasterPages/Test.master" AutoEventWireup="true" Inherits="TestPage" Codebehind="TestPage.aspx.cs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="phContent" Runat="Server">
<asp:Literal ID="litTest" runat="server" />
</asp:Content>
使用代码隐藏,例如:
public partial class TestPage : System.Web.UI.Page, IContentInjectable
{
public Literal ExposedLiteral
{
get
{
return litTest;
}
}
}
您的母版页代码隐藏可能是这样的:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
IContentInjectable icPage = this.Page as IContentInjectable;
if (icPage != null)
{
icPage.ExposedLiteral.Text = "Test Text";
}
}
【讨论】: