如何从asp.net 2.0中的页面调用用户控件的方法?
我有一个在母版页中使用的用户控件。 我添加了一个带有母版页的页面。
现在我需要从页面调用用户控件的方法。 如何做到这一点?请帮忙。
I have a usercontrol used in a masterpage.
I have added a page with the masterpage.
Now I need to call a method of the user control from the page.
How to do this? Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您的方法是公共的并且您的用户控件的类型是 YourUserControlsType,请尝试以下操作:
Assuming that your method is public and your user control's type is YourUserControlsType, try this :
即使它是以编程方式添加的,这也应该让您获得控制权:
在您添加的页面的成员中:
This should get you your control even if it was added programatically:
In a member of the page you added:
如果您没有对该控件的成员引用,则应考虑将页面与控件分离。在理想情况下,页面不一定知道它可能包含或可能不包含的控件。因此,您可能会考虑 MVP 模式的实现。
这里有一个简单的 MVP 实现,您可以此处查看解耦过程。如果您从解耦示例中反转通信(即页面触发控件拾取的事件),那么基本上,您已经将页面与控件解耦了。这样做的好处是,如果您的页面发生更改并且不再使用该控件,则任何事件都不会拾取该事件,并且您的页面将继续执行,不会出现任何问题。我发现这比 FindControl 找不到控件然后您尝试对其执行方法时潜在的空引用异常更合适。
虽然解耦可能需要额外几分钟的时间,但在许多情况下,这是值得付出的努力。
If you don't have a member reference to the control you should consider decoupling the page from the control. In an ideal world, the page should not necessarily know about a control it may or may not contain. Therefore, you might look into an implementation of the MVP pattern.
There's a simple implementation of MVP here, and you can see the decoupling in action here. If you reverse the communication from the decoupling example (i.e. page fires an event that the control picks up), then basically, you've decoupled your page from the control. This has a benefit in that if your page changes and the control is no longer in use, the event is not picked up by anything and your page continues to execute with no problems. I find this much more suitable than a potential null reference exception when FindControl doesn't find the control and then you try to execute a method on it.
While decoupling may take a few extra minutes, in many scenarios it turns out to be a worthwhile endeavor.