2010-01-14 2 views
1

좋은 제목을 찾을 수 없습니다. 간단한 ASP.NET 3.5 폼이 있습니다. 번호가 매겨진 주석을 따르는 경우 디버그 모드에서 페이지를 실행할 때 코드를 어떻게 진행하는지 설명합니다. 아래 함수는 모두 페이지의 코드 숨김 파일에서 선언 된 메서드이며 둘 다 같은 _Default 클래스에 있습니다. ManagersListBox는 Default.aspx 페이지에 선언되어 있습니다. GetSubordinates 컨텍스트에서 ManagersListBox가 null 인 이유는 무엇입니까? 마치 잠시 사라진 것처럼 보이고 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

답변

3

Microsoft article 보면 IT는 경우 SelectMethod이 코드에서 호출 될 때 새로운 페이지 인스턴스가 만들어 질 것 같습니다 및이 방법이 사용됩니다.

는 인스턴스 메소드 경우는 비즈니스 객체가 생성되고 이 경우 SelectMethod 속성에 의해 지정된 인 메소드를 호출 할 때마다 파괴.

페이지 클래스의 별도 인스턴스이므로 원본 페이지의 컨트롤에 액세스 할 수 없습니다. 또한 이것은 페이지 클래스의 인스턴스이며 페이지 라이프 사이클의 일부로 실행되지 않으므로 관련 컨트롤은 초기화되지 않습니다.
이 방법을 매개 변수화하는 것이 최선의 방법입니다.

+0

완전히 의미가 있습니다. 이런 종류의 것은 새로운 페이지 인스턴스를 불필요하게 다루는 것을 피하기 위해 가능하면 정적 메서드를 사용해야하며, 또는 그것이 처음부터 소속 된 별도의 비즈니스 클래스에 배치해야 함을 의미합니다. – AaronLS

관련 문제