是否可以在asp.net WebFroms中从特定页面子类继承的页面的page_load事件中调用函数?

时间:2017-03-30 20:29:56

标签: c# asp.net webforms

我想在每个Page_load的{​​{1}}事件上执行一个函数,从中派生我自己的System.Web.UI.Page类(显然也继承自CustomPage类)

到目前为止,我已经创建了Page这样的类:

CustomPage

在派生的public class CustomPage : System.Web.UI.Page { protected virtual void Page_Load(object sender, EventArgs e) { CallTOTheDesiredFunction(); //this is the call to the function I want } } 类中,我这样做:

Page

很明显,这种方法有效,但它不是最好的解决方案,因为我必须在每个派生页面上调用public class DerivedPage : CustomPage { protected override void Page_Load(object sender, EventArgs e) { base.Page_Load(sender, e); //the rest of the page load event which executes from here on } }

对于我想要实现的目标,是否有更好的解决方案? 提前谢谢

1 个答案:

答案 0 :(得分:2)

是。最好覆盖Onload方法,而不是依赖派生类来调用基本方法。

您仍然可以在每个页面中挂钩Load事件,但请使用基类中的方法。

public class CustomPage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        CallTOTheDesiredFunction();  //this is the call to the function I want

        base.OnLoad(e);
    }
}