2011-03-19 141 views
7

爲什麼DisplayUsers();不起作用?Page_Load vs OnLoad

我的基地頁:

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()不起作用,

+1

我不太瞭解使用UI.Page作爲基類而不是真正的業務邏輯。這是一個網絡演示應用程序。所有的基本邏輯應該與演示文稿分開。 – Independent 2011-03-19 19:38:17

+0

@dingir - 舉個例子吧! – eyalb 2011-03-19 19:48:30

+3

使用'PascalCase'命名空間,類型名稱等等。您可以稍後感謝我。 – 2011-03-19 19:54:40

回答

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

在執行的代碼,沒有什麼區別,但

  • AutoEventWireup應該啓用(通常以標記)每頁
  • Page_Load(和other events這樣)使用自動事件訂閱mechanism,它使用反射,什麼稍微打性能

我個人建議重寫OnLoad(),只是不要忘記調用base

3

根據.NET應用程序Performance Tips and Tricks

避免Autoeventwireup功能

不是依靠autoeventwireup,從頁面重載的事件。例如,而不是編寫Page_Load()方法,請嘗試重載public void OnLoad()方法。這允許運行時從每個頁面執行CreateDelegate()。