为每个 Page_Load 运行代码
我需要对 ASP.NET 应用程序中的每个加载页面进行 HTML 代码操作。放置我的方法的最佳位置在哪里?将代码放入每个网页的 Page_Load 事件中不是很聪明,还有什么其他选择?
I need to do HTML code manipulation for every loaded page in my ASP.NET application. Where is the best place to put my method? Put code into every web page Page_Load event in not very smart, what other alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我的理解正确,那么逻辑上您需要在 Page_Load 中发生一些事情,但您希望避免在每种情况下重复该代码的明显问题。
我将为项目定义一个页面库(这样做还有其他优点),所有页面代码隐藏都继承自该页面库,并且该页面库本身也继承自 System.Web.UI.Page。然后,让它在 Page_Load 之前或之后根据需要完成所需的工作。
或者,也可以在过滤器中完成您所说的 HTML 操作工作。
If I get you right, you've something which logically needs to happen in Page_Load, but you want to avoid the obvious issues with duplicating that code in each case.
I would define a page base for the project (there are other advantages in doing so too), that all page code-behinds inherit from, and which itself inherits from System.Web.UI.Page. Then, have it do the required work before or after the Page_Load as appropriate.
Alternatively, it may be possible to do the HTML manipulation work you talk of in a filter.
考虑使用自定义 HttpModule
http://msdn.microsoft.com/en-us/library /ms227673.aspx
或在 Global.asax 中,您可以在 Application_PreRequestHandlerExecute 中挂钩所需的事件:
consider using custom HttpModule
http://msdn.microsoft.com/en-us/library/ms227673.aspx
or in Global.asax you can hook up desired event in Application_PreRequestHandlerExecute:
创建一个继承 System.Web.UI.Page 的新基类,然后在每个代码隐藏页面中,将它们更新为从这个新基类继承,而不是 System.Web.UI.Page。
在这个新的基类中,您可以粘贴可以从所有页面上的 Page_Load 调用的方法。
Create a new base class which inherits System.Web.UI.Page, then in each of your code behind pages, update them to inherit from this new base class rather than System.Web.UI.Page.
In this new base class you can stick the method which you can call from the Page_Load on all of your pages.
我会编写一次 JavaScript 函数并将其导入到每个页面中。
I'd write a JavaScript function once and import it into every page.