简体   繁体   English

为每个Page_Load运行代码

[英]Run code for every Page_Load

I need to do HTML code manipulation for every loaded page in my ASP.NET application. 我需要为ASP.NET应用程序中的每个加载页面执行HTML代码操作。 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? 把代码放到每个网页的Page_Load事件中都不是很聪明,还有什么其他选择?

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. 如果我说得对,你在Page_Load中有一些逻辑上需要发生的东西,但你想避免在每种情况下复制代码的明显问题。

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. 我将为项目定义一个页面基础(这样做也有其他优点),所有页面代码隐藏继承自,并且它本身继承自System.Web.UI.Page。 Then, have it do the required work before or after the Page_Load as appropriate. 然后,让它在适当的Page_Load之前或之后完成所需的工作。

Alternatively, it may be possible to do the HTML manipulation work you talk of in a filter. 或者,也可以在过滤器中执行您所讨论的HTML操作工作。

consider using custom HttpModule 考虑使用自定义HttpModule

http://msdn.microsoft.com/en-us/library/ms227673.aspx http://msdn.microsoft.com/en-us/library/ms227673.aspx

or in Global.asax you can hook up desired event in Application_PreRequestHandlerExecute: 或者在Global.asax中,您可以在Application_PreRequestHandlerExecute中挂接所需的事件:

void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;

            if (context.Handler is Page)
            {
                Page page = (Page)context.Handler;
                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. 创建一个继承System.Web.UI.Page的新基类,然后在每个页面后面的代码中更新它们以继承这个新的基类而不是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. 在这个新的基类中,您可以在所有页面上粘贴可以从Page_Load调用的方法。

我会编写一次JavaScript函数并将其导入每个页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM