ObjectDataSource 的 Select 方法中 ListBox 为 null

Aar*_*nLS 2 c# asp.net

我想不出一个好的主题。我有一个简单的 ASP.NET 3.5 表单。如果您遵循编号注释,我将解释当我在调试模式下运行页面时如何单步执行代码。以下两个函数都是在页面的代码隐藏文件中声明的方法,都位于同一个 _Default 类中。ManagersListBox 在 Default.aspx 页面中声明。为什么在 GetSuborders 的上下文中,ManagersListBox 为空?就好像它消失了一会儿,然后在从 GetSubscribeds 方法返回后又重新出现了。显然,解决方案是参数化 GetSuborindates,但这不是我关心的。我正在尝试了解 ASP.NET 的工作原理,并且我真的很想了解为什么我会看到这种“对象消失”的行为。谢谢。

    <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>
Run Code Online (Sandbox Code Playgroud)

文件背后的代码:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ose 5

查看这篇Microsoft 文章,当在代码中调用 SelectMethod 时,会创建一个新的页面实例并使用此方法。

如果它是实例方法,则每次调用 SelectMethod 属性指定的方法时都会创建并销毁业务对象。

由于这是页面类的单独实例,因此您将无权访问原始页面上的控件。此外,由于这是页面类的实例并且不作为页面生命周期的一部分运行,因此它的相关控件都不会被初始化。
看起来参数化这个方法是你最好的选择。