从后面的子母版页代码访问子母版页上的用户控件

时间:2009-09-03 13:44:29

标签: c# asp.net master-pages

尝试通过同一母版页后面的代码在我的子母版页面上设置文字用户控件的值。

以下是我正在使用的代码示例:

Global.master

<form id="form1" runat="server">
<div>
    <asp:ContentPlaceHolder id="GlobalContentPlaceHolderBody" runat="server">

    </asp:ContentPlaceHolder>
</div>
</form>

Template.master(Global.master的孩子)

<asp:Content ID="TemplateContentBody" ContentPlaceHolderID="GlobalContentPlaceHolderBody" Runat="Server">
<asp:Literal ID="MyLiteral1" runat="Server"></asp:Literal>

<p>This is template sample content!</p>
  <asp:ContentPlaceHolder ID="TemplateContentPlaceHolderBody" runat="server">

</asp:ContentPlaceHolder>

Template.master.cs

    protected void Page_Load(object sender, EventArgs e)
{
    MyLiteral1.Text = "Test";
}

ContentPage.aspx

< asp:Content ID="ContentBody" ContentPlaceHolderID="TemplateContentPlaceHolderBody" Runat="Server">
</asp:Content>

一旦我能够实现这一目标,我还需要能够通过内容页面访问全局和模板母版页上的内容。

3 个答案:

答案 0 :(得分:3)

如果我了解您的方案,您希望让您的内容页面访问母版页中的项目。如果是这样,您需要设置一个属性以在母版页中公开它们,并在内容页面中设置MasterType指令。

this post为例说明一下。

答案 1 :(得分:1)

找到了一个有效的解决方案在template.master(嵌套子master)中,我不得不将代码放在OnLoad事件中。

protected override void OnLoad(EventArgs e)
{
    MyLiteral1.Text= "<p>MyLiteral1 Successfully updated from nested template!</p>";
    base.OnLoad(e);
}

很奇怪......

基本上,我使用全局主页作为在每个页面上共享代码的页面,然后我将有各种嵌套页面以适应每个网站部分。对于导航嵌套模板,我希望能够显示用户是否已登录以及购物车中有多少项。

如果有更好的方法可以实现这一目标,我愿意接受建议。

答案 2 :(得分:0)

编辑:当我以为你试图从后面的父母代码访问子母版的控件时,这是我的答案。

您可以使用递归findControl函数:

protected Control FindControlRecursive(string id, Control parent)
{
    // If parent is the control we're looking for, return it
    if (string.Compare(parent.ID, id, true) == 0)
        return parent;

    // Search through children
    foreach (Control child in parent.Controls)
    {
        Control match = FindControlRecursive(id, child);

        if (match != null)
            return match;
    }

    // If we reach here then no control with id was found
    return null;
}

然后在您的母版页中使用此代码:

protected void Page_Load(object sender, EventArgs e)
{
//EDIT: if GlobalContentPlaceHolderBody isn't visible here, use this instead:
//Control c = FindControlRecursive("MyLiteral1", Page.FindControl("GlobalContentPlaceHolderBody"));
    Control c = FindControlRecursive("MyLiteral1", GlobalContentPlaceHolderBody);
    if(c != null)
        ((Literal)c).Text = "Test";
}