如何从子页面控制 ASP.NET 母版页上的元素
我的 asp.net 网站上有几个页面,我想关闭母版页上的控件。 有没有办法从子页面与母版页进行通信?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单的方法是在母版页上设置一个属性,用于在调用时处理开/关功能。 然后在您的子页面中设置 MasterType 指令 以获取强类型引用到您的母版页以绕过强制转换的需要。
您的子页面将具有:
并调用母版页的属性:
因此在您的母版页上您可以具有:
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:
And to call the property of the master page:
So on your master you could have:
您需要在页面标记中使用 MasterType 指令
然后您将能够使用访问页面母版页的任何公共属性
希望这会有所帮助
You need to use a MasterType directive in your page markup
Then you will be able to access any public properties of the page's master page using
Hope this helps
以下是如何从子页面与母版页进行通信的示例。
在母版页中,为您要访问的控件创建一个属性,例如名为 lblUser 的标签...
在子页面中,访问您刚刚创建的属性,如下例所示...
我们能够做到这一点因为Master只是一个继承System.Web.UI.MasterPage的类。
我们创建的 Label.Text 属性只是 Master 类的一个属性(该名称将是当前母版页的具体名称,在本例中为 MyMaster)。
请注意,如果没有转换到特定的母版页类,它就无法工作,这是因为您添加了一个在 System.Web.UI.MasterPage(this.Master 的类型)中不存在的字段,但在您的特定母版页类中。
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...
In the child page, access the property you have just created as in the following example...
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.
我一直在寻找类似的东西,但这个解决方案似乎不适合我。 我有一个嵌套的母版页。 这对嵌套大师有用吗? 当我实现时,它无法识别我添加到主控中的控件。
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.