Page_Load vs OnLoad

时间:2011-03-19 19:28:57

标签: c# .net asp.net page-lifecycle

为什么DisplayUsers();不起作用?

我的基页是:

public class adminPage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        if (User.Identity.IsAuthenticated == false) { Response.Redirect("~/Account/login.aspx?ReturnUrl=/admin"); };
        if (!(User.IsInRole("admin") || User.IsInRole("super user"))) { Response.Redirect("/"); };
    }        
  }

我的班级是

public partial class users : adminPage
{ 
    protected void Page_Load(object sender, EventArgs e)
    {                        
        string sName;
        adminGeneralData.GetToolData(2, out sName);
        pageH1.Text = sName;

        DisplayUsers();
    }

    protected void DisplayUsers()
    {
        DataSet ds = userData.GetUsersData();
        userList.DataSource = ds;
        userList.DataBind();
    }
}

DisplayUsers()不起作用,

3 个答案:

答案 0 :(得分:16)

如果我没记错的话,你需要调用基类的OnLoad事件来正确注册Page_Load事件:

protected override void OnLoad(EventArgs e)
{
    if (User.Identity.IsAuthenticated == false) { Response.Redirect("~/Account/login.aspx?ReturnUrl=/admin"); };
    if (!(User.IsInRole("admin") || User.IsInRole("super user"))) { Response.Redirect("/"); };

    base.OnLoad(e);
}

以下是一些好的读物:

答案 1 :(得分:3)

根据.NET应用程序中的Performance Tips and Tricks

  

避免使用Autoeventwireup功能

     

不依赖于autoeventwireup,而是覆盖Page的事件。例如,而不是编写Page_Load()方法,请尝试重载public void OnLoad()方法。这允许运行时必须为每个页面执行CreateDelegate()。

答案 2 :(得分:1)

在执行的代码中,没有区别,但是

  • AutoEventWireup应为每个页面启用(通常在标记中)
  • Page_Load(和other events一样)使用自动事件订阅mechanism,它使用反射,略微达到性能

我个人建议覆盖OnLoad(),不要忘记致电base