2014-10-29 78 views
-1

我有以下代码。在页面加载期间,我从数据库中获取客户对象。之后,当我尝试以不同的方法访问同一个对象时,该对象变为空白。假设Student对象的firstName一样的属性,姓氏等如何防止对象变为空?

Public class Test 

    Public oStudent as Student 

    Public Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load 
     oStudent = getStudent(22) 'This is just a sample. This is not my actual database. 

    End Sub 

    Public Sub Update(ByVal sender as Object, ByVal e as System.EventArgs) Handles crtlStudent.Update 
     Update(oStudent)'This one updates makes a database call to update the studnet 

    End Sub 
End class 

页面加载时,学生从数据库中正确返回。但是,当我使用我的更新方法时,oStudent对象变为空/空。这是页面生命周期的工作方式吗?如果是的话,我需要将学生存储在一个会话中或缓存它的权利?有没有其他的方法来防止学生变成空的,使用会话变量或缓存它?

+0

网络是无状态的。对这个话题做一些研究,这已经为我的口味讨论了太多次了......你可能会考虑切换到MVC,只是为了理解实际发生的事情。 – walther 2014-10-29 15:12:37

+0

在这些情况下,我只是'欺骗',并在表单中使用隐藏的元素来保存值,这样它在回发期间保持在viewstate中。变量在回发完成后总是失去它们的值。 – Zack 2014-10-29 15:59:05

回答

2

在另一种方法中,对象不是null,而是在页面处理完成后。这发生在每个页面生命周期的末尾,所以当它呈现为HTML并发送到客户端时。

因此,您必须在每次回发时重新初始化/加载对象或将其保存在某处。在您的示例代码中,您总是在Page_Load中加载它,因此我怀疑它是否在任何地方都是null。所以我想,这不是真正的代码可能是:

Public Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load 
    If Not IsPostBack Then 
     oStudent = getStudent(22) ' in a button-click handler it will be null since it's a PostBack 
    End If 
End Sub 

是否有任何其他的方式来防止oStudent成为空 其他使用会话变量或缓存呢?

Nine Options for Managing Persistent User State in Your ASP.NET Application