ASP.NET - Accessing Master Page elements form the Content Page

梦想与她 提交于 2020-01-12 07:58:09

问题


Can the elements of the Master Page be accessed from the Content Page?

Lets say I have MasterPage1 and ContentPage1 that inherits from the MasterPage1, and the MasterPage1 has a button: Button1.

Can I change the property of that button from the content page, for example to make Button1 invisible, inactive etc? How can I accomplish this?

I am using .net2.0


回答1:


You have to put a reference to the MasterPage in your page/user control markup.

<%@ Reference VirtualPath="..." %>

Then in the code-behind, you just cast the Page.MasterPage to your MasterPage and access its properties.

MyMasterPage myMasterPage = (MyMasterPage)Page.Master;



回答2:


Yes...if you need to do this from the aspx page using the MasterPage it would be:

Button myButton = (Button)Master.FindControl("myButton");
myButton.Visible = false;



回答3:


Master.FindControl("myButton").Visible = False

Be careful that the control that you use to run the above command, should not be inside an Update panel.




回答4:


Yes they can, and there are a few approaches to this.

The approach I use is to create public methods within the master page that will do the modification/access to the data within the master page. For example, I typically like to modify the link style of the current page/category I am on, so I have a method in my master page like this:

   Public Sub SetNavigationPage(ByVal MenuName As String)

      DirectCast(Me.FindControl(MenuName), HyperLink).CssClass = "MenuCurrent"

   End Sub

Then in my content page, I simply access this method as such:

Dim myMaster As EAF = DirectCast(Me.Master, EAF)
myMaster.SetNavigationPage("hypViewEmployee")

...where EAF is the name of the class of my master page.

One interesting issue I've found is that I've had complications with using the Visibility property of .NET controls when trying to show/hide them in this manner. This is due to the rendering orer of master and content pages. To resolve this, I setup a basic CSS style for both visible and hidden and set the CssClass property accordingly.



来源:https://stackoverflow.com/questions/461911/asp-net-accessing-master-page-elements-form-the-content-page

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