以编程方式设置ASP:ContentPlaceHolder内容

时间:2008-11-14 19:02:03

标签: c# asp.net contentplaceholder

以编程方式设置<asp:ContentPlaceHolder>内容的最简单方法是什么?我想生病了Master.FindControl电话?

3 个答案:

答案 0 :(得分:4)

如果您的页面继承自MasterPage,那么您的页面上应该有一个带有ID的asp:Content控件,如下所示:

<asp:Content runat="server" ID="myContent" ContentPlaceHolderID="masterContent">
</asp:Content>

您应该能够在代码隐藏中引用它,并添加您想要的任何内容。

public void Page_Load( object sender, EventArgs e )
{
    HtmlContainerControl div = new HtmlGenericControl( "DIV" );
    div.innerHTML = "....whatever...";
    myContent.Controls.Clear();
    myContent.Controls.Add(div);
}

答案 1 :(得分:0)

如果您要将控件添加到空白页面,那么您可以执行Page.Controls.Add().... no?

答案 2 :(得分:0)

我使用自定义扩展方法以递归方式搜索控件(例如占位符)以找到您正在寻找的控件并返回它。然后,您可以根据需要填充返回的控件。在foreach循环中调用此方法迭代您的控件列表以填充。

public static class ControlExtensions
{
    /// <summary>
    /// recursive control search (extension method)
    /// </summary>
    public static Control FindControl(this Control control, string Id, ref Control found)
    {
        if (control.ID == Id)
        {
            found = control;
        }
        else
        {
            if (control.FindControl(Id) != null)
            {
                found = control.FindControl(Id);
                return found;
            }
            else
            {
                foreach (Control c in control.Controls)
                {
                    if (found == null)
                        c.FindControl(Id, ref found);
                    else
                        break;
                }

            }
        }
        return found;
    }
}