2010-01-14 62 views
1

我無法想出一個好主題。我有一個簡單的ASP.NET 3.5表單。如果您遵循編號的註釋,我將解釋在調試模式下運行頁面時,我是如何跨越代碼的。下面的兩個函數都是在頁面文件後面的代碼中聲明的方法,它們都在同一個_Default類中。 ManagersListBox在Default.aspx頁面中聲明。爲什麼在GetSubordinates的上下文中,ManagersListBox是空的?就好像它消失了一會兒,然後從GetSubordinates方法返回後再次出現。顯然,解決方案是參數化GetSuborindates,但這不是我關心的問題。我想了解ASP.NET如何工作,我真的很想了解爲什麼我看到這種行爲「消失的對象」。謝謝。ListBox在ObjectDataSource的Select方法中爲null

隱藏文件
<asp:ListBox ID="ManagersListBox" runat="server" Width="293px" 
     DataTextField="LoginID" DataSourceID="ObjectDataSource2" 
     DataValueField="EmployeeID" onload="ManagersListBox_Load"      
     AutoPostBack="true" onprerender="ManagersListBox_PreRender"></asp:ListBox> 


    <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" 
     SelectMethod="GetSubordinates" TypeName="WebApplication._Default"> 
    </asp:ObjectDataSource> 

代碼:

protected void ManagersListBox_PreRender(object sender, EventArgs e) 
{ 

    if (ManagersListBox != null) 
    { 
     //1. Right here, ManagersListBox is not null 
    } 

    //2. This call causes the ObjectDataSource to call GetSubordinates 
    ObjectDataSource2.Select(); 
    //4. After stepping out of GetSubordinates and back here, 
    // ManagersListBox is again non-null. 
} 

public List<DataModel.Employee> GetSubordinates()//int ManagerID) 
{ 
    //3. ManagersListBox is always null here 
    using (DataModel.AdventureWorksEntities entities = new DataModel.AdventureWorksEntities()) 
    {     
     if (ManagersListBox != null) 
     { 

      return (from employee in entities.Employees 
        where employee.Manager.EmployeeID == Convert.ToInt32(ManagersListBox.SelectedValue) 
        select employee).ToList(); 
     } 
     else 
     { 
      return (from employee in entities.Employees        
        select employee).ToList(); 
     } 
    } 
} 
+0

不是一個完整的答案,但你也可以檢查我的答案在這裏:http://stackoverflow.com/questions/32642032/wrestling-with-objectdatasource-other-controls-and-variables-not-defined/32715967#32715967 – Canavar 2015-09-22 11:45:38

回答

3

望着這Microsoft article看來,當SelectMethod被稱爲在你的代碼中創建一個新的頁面實例,並使用這種方法。

如果它是一個實例方法,則 業務對象被創建並 每個由SelectMethod屬性指定 的 方法被調用時被破壞。

由於這是頁面類的獨立實例,因此您無法訪問原始頁面上的控件。同樣,因爲這是頁面類的一個實例,並且不作爲頁面生命週期的一部分運行,所以它的相關控件都不會被初始化。
它看起來像參數化這種方法是你最好的選擇。

+0

現在完全合理。這意味着我應該在可能的情況下使用靜態方法,並且/或者將它放在一個獨立的業務類中,以避免新的頁面實例不必要的新增。 – AaronLS 2010-01-14 21:50:29