c# - ObjectDataSource 的 Select 方法中 ListBox 为 null

标签 c# asp.net

我想不出一个好的主题。我有一个简单的 ASP.NET 3.5 表单。如果您遵循编号注释,我将解释当我在 Debug模式下运行页面时如何单步执行代码。以下两个函数都是在页面的代码隐藏文件中声明的方法,都位于同一个 _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>

文件隐藏代码:

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();
        }
    }
}

最佳答案

看着这个Microsoft article看起来,当在代码中调用 SelectMethod 时,会创建一个新的页面实例并使用此方法。

If it is an instance method, the business object is created and destroyed each time the method that is specified by the SelectMethod property is called.

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

关于c# - ObjectDataSource 的 Select 方法中 ListBox 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2062600/

相关文章:

c# - 当对象是 Task<Something> 时获取 Func<object> 的结果

c# - 如何在 aspnet.core web api 中验证 JWT token ?

javascript - SWFUpload ASP.Net 示例站点不工作?

c# - Controller 中的 ASP NET MVC 数组到客户端数组

c# - 检测服务器和SQL Server错误并显示错误页面

c# - 以 HttpMethod 作为参数的泛型方法

c# - 在 RDotNet.dll 中发生类型为 'System.StackOverflowException' 的未处理异常以在 Web 应用程序中加载 R 库

c# - 特定属性的 SequenceEqual

asp.net - SQL如何在一列中使用ORDER BY语句

c# - 旋转 log4net 不会重写相同的日志文件