Set ASP:ContentPlaceHolder Content programmatically

时光总嘲笑我的痴心妄想 提交于 2019-12-08 04:43:31

问题


What is the easiest way to set the contents of an <asp:ContentPlaceHolder> programmatically? I imagine ill have to do a Master.FindControl call?


回答1:


If your page inherits from a MasterPage, then you should have an asp:Content control on your page with some id, like so:

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

You should be able to reference this in your codebehind and add whatever you want to it.

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



回答2:


If you are adding controls to a blank page then you do Page.Controls.Add()....no?




回答3:


I use a custom extension method that searches a control (a placeholder for example) recursively to find the control you're looking for by Id and return it. You can then populate the returned control as required. Call this in a foreach loop iterating over your list of controls to populate.

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;
    }
}


来源:https://stackoverflow.com/questions/291037/set-aspcontentplaceholder-content-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!