How can I get the parent page from a User Control in an ASP.NET Website (not Web Application)

后端 未结 9 1027
别跟我提以往
别跟我提以往 2020-12-15 16:54

Just as the subject asks.

EDIT 1

Maybe it\'s possible sometime while the request is being processed to store a reference to the parent page in the user contr

相关标签:
9条回答
  • 2020-12-15 17:10

    You must use NamingContainer like that:

           try
            {
                if (!string.IsNullOrWhiteSpace(TargetCtrlID))
                {
                    var ctrl = NamingContainer.FindControl(TargetCtrlID);
                    if(ctrl != null)
                        Console.Write("'" + ctrl.ClientID + "'");
                }
            }
            catch
            {
    
            }
    
    0 讨论(0)
  • 2020-12-15 17:12

    Writing to Page and Master Page from Web User Control: Personally I like the user controls to be loose, but it can be done like this.

    Master Page:

    public partial class Second : System.Web.UI.MasterPage
        {
            public void SecondMasterString(string text)
            {
                MasterOut.Text += text;
            }
        }
    

    Directive needed on WebForm1 : So page can write to master page

    <%@  MasterType VirtualPath="~/DemoFolder/MasterPages/Second.master" %>
    

    Methods write to page and Master Page:

    public partial class WebForm1 : System.Web.UI.Page
        {
        public void SetPageOutput(string text)
            {
                // writes to page
                this.PageOut.Text = text;
            }
    
            public void SetMaster(string text)
            {
                // writes to Master Page
                this.Master.SecondMasterString(text);
            }
    }
    

    User Control writes to both Page and Master Page:

    public partial class WebUserControl1 : System.Web.UI.UserControl
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                LegoLand.DemoFolder.MasterPages.WebForm1 page = (WebForm1)this.Parent.Page;
                page.SetMaster("** From the control to the master");
                page.SetPageOutput("From the control to the page");
            }
        }
    
    0 讨论(0)
  • 2020-12-15 17:18

    Every control has a parent property that you can use to access the parent.

    protected void Page_Load(object sender, EventArgs e)
    {
      Response.Write(this.Parent.ID);
    }
    

    EDIT: depends on which one of the lifecycle events of the page you want to store the reference and what use to store that reference. However the reference is always available

    0 讨论(0)
提交回复
热议问题