开发者

Run code for every Page_Load

I need to do HTML code manipulation for every loaded page in my ASP.NE开发者_如何学运维T 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?


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.


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:

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.

In this new base class you can stick the method which you can call from the Page_Load on all of your pages.


I'd write a JavaScript function once and import it into every page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜