ASP.NET - 内容页可以调用其母版页中的函数吗?
我有一个带有母版页的网站,Site.master。 Site.master 的许多内容页面都有相同的按钮,每个页面上的功能都相同:
是否可以在 Site.master 的 CodeFile 中编写一次 btn_Click
并在每个内容页按钮的 OnClick 属性中调用它?我试图避免向每个内容页面的 CodeFile 添加相同的函数(或任何东西)。
谢谢!
I have a site with a master page, Site.master. Many of Site.master's content pages have the same button that functions the same way on each page:
<asp:ImageButton ID="btn" runat="server" OnClick="btn_Click" />
Is it possible to write btn_Click
once in Site.master's CodeFile and have it called in the OnClick attribute of each content page's button? I'm trying to avoid adding the same function (or anything at all) to each content page's CodeFile.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是可行的,但作为最佳实践,如果您有意识地选择在母版页中保留尽可能多的功能,您将为自己省去很多麻烦。保留它们用于演示和单独演示。使用基页面类和用户控件在页面级别执行操作可能会更好(特别是如果它是通用操作)
It's doable, but as a best practice you'll save yourself a lot of heartache if you just make a conscious choice to keep as much functionality out of your master pages as possible. Reserve them for presentation and presentation alone. You might be better served using base page classes and user controls to perform actions at the page level (especially if it is a universal action)
如果按钮几乎相同,您可以将它们放入 Master 页面(或 SubMaster 页面)。
否则,使用 MasterType 您可以强类型 Page.Master 属性。 也许可以连接一个按钮,例如:
如果没有,您可以让 Master 搜索具有已知 ID 的控件并将其连接起来。
If the buttons are pretty much identical, you could just put them into the Master page (or a SubMaster page).
Otherwise, with MasterType you can strong type the Page.Master property. It may be possible to wire up a button like:
If not, you could have the Master search for a control with a known ID and hook it up.
可以,但是不太漂亮。更好的方法是让您的内容页面派生自一个继承自 Page 的公共基类。您可以在那里放置所有页面通用的代码。
You can, but it's not pretty. A better way is to make your content pages derive from a common base class that inherits from Page. There you can put code that's common to all pages.
如果该按钮位于每个页面上,是否有某种原因不实际将按钮放入母版中?
如果这是不可能的,我建议创建一个新的类文件(例如,
FooButtonBehavior
),然后将按钮处理程序放入该类中(例如,OnFooClicked()
)。然后在每个类的代码隐藏中新建一个FooButtonBehavior
实例并调用OnFooClicked()
。如果您需要传入在页面上操作的任何控件,您也可以这样做。If the button is on every page, is there some reason not to actually put the button in the Master?
If this isn't possible, I would recommend creating a new class file (e.g.,
FooButtonBehavior
) then put your button handler in that class (e.g.,OnFooClicked()
). Then in your code-behind for each class just new up an instance ofFooButtonBehavior
and callOnFooClicked()
. If you need to pass in any controls that get manipulated on the page, you can do that as well.为什么不将 ImageButton 及其单击处理程序封装到 UserControl 中?那么您就不必重复任何代码。
Why not encapsulate the ImageButton and it's click handler into a UserControl? Then you won't have to repeat any code.