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

非 Y 不嫁゛ 提交于 2019-12-28 11:49:14

问题


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?


回答1:


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



回答2:


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




回答3:


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.




回答4:


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.




回答5:


this.Master.FindControl("controlid").dosomethinghere


来源:https://stackoverflow.com/questions/1092784/how-to-control-elements-on-a-asp-net-master-page-from-child-page

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