How to control elements on a asp.net master page from child page

前端 未结 5 1704
野趣味
野趣味 2020-12-08 12:33

I have a few pages on my asp.net website that I would like to turn off a control on the master page. Is there a way to communicate with the master page from a child page?

相关标签:
5条回答
  • 2020-12-08 12:46

    I was looking for something similar, but this solution doesn't seem to work for me. I have a nested master page. Does this work for a nested master? When I implemented, it's not recognizing the control that I added to my master.

    0 讨论(0)
  • 2020-12-08 12:56

    Easiest way is to setup a property on your master page that handles the on/off functionality when called. Then in your child page set the MasterType directive to get a strongly typed reference to your master page to bypass the need to cast.

    Your child page would have:

    <%@ MasterType VirtualPath="~/Site1.Master" %>
    

    And to call the property of the master page:

    Master.MyLabel = false; // or true
    

    So on your master you could have:

    public bool MyLabel
    {
        get
        {
            return masterLabel.Enabled;
        }
        set
        {
            masterLabel.Enabled = value;
        }
    }
    
    0 讨论(0)
  • 2020-12-08 13:07
    this.Master.FindControl("controlid").dosomethinghere
    
    0 讨论(0)
  • 2020-12-08 13:10

    You need to use a MasterType directive in your page markup

    <%@ MasterType TypeName="Namespace.Etc.MyMasterPage" %>
    

    Then you will be able to access any public properties of the page's master page using

    this.Master.PropertyIWantToIntefereWith...
    

    Hope this helps

    0 讨论(0)
  • 2020-12-08 13:10

    Here's an example of how to communicate with Master Pages from Child Pages.

    In the master page, create a property for the control you wish to access, say a label called lblUser...

    public string MyProperty
           {
            set { lblUser.Text = value; }
           }
    

    In the child page, access the property you have just created as in the following example...

    ((MyMaster)this.Master).MyProperty = "Text changed from Sub Page";
    

    We are able to do this because the Master is simply a class that inherits System.Web.UI.MasterPage.

    And the Label.Text property that we created is just a property of the Master class (this name will be the specific name of your current Master Page, in this case MyMaster).

    Notice it won't work without a cast to your specific Master Page class and this is because you added a field that does not exist in System.Web.UI.MasterPage, the type of this.Master, but in your specific Master Class.

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