【问题标题】:How to prevent the object from becoming null?如何防止对象变为空?
【发布时间】:2014-10-29 15:11:00
【问题描述】:

我有以下代码。在页面加载期间,我从数据库中获取客户对象。之后,当我尝试以不同的方法访问同一个对象时,该对象显示为空。假设 Student 对象具有 firstName、lastName 等属性。

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 对象变为空/空。这是页面生命周期的工作方式吗?如果是,我需要将 oStudent 存储在会话中或缓存它吗?有没有其他方法可以防止 oStudent 变为 null 其他使用会话变量或缓存它?

【问题讨论】:

  • Web 是无状态的。对该主题进行一些研究,这已经讨论了太多次了,我的口味已经……您可以考虑切换到 MVC,只是为了了解实际发生的情况。
  • 在这种情况下,我只是“作弊”并使用表单中的隐藏元素来保存值,这样它在回发期间保持在视图状态中。回发完成后,变量总是会丢失其值。

标签: asp.net vb.net webforms


【解决方案1】:

在其他方法中对象不是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 变为 null 其他使用会话变量或缓存它?

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

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多