简体   繁体   中英

How to create a Session Variable in a Public Property using VB.Net

I have already asked a similar question earlier, but this is doing my head in! On ASPX Page, I have this property:

Public ReadOnly BreadQuestionnaire as Bread 
                          Implements IQuestionnaire.BreadQuestionnaire
       Get
           If Me.Session("BreadQuestionnaire") Is Nothing Then
              Me.Session("BreadQuestionnaire") = New Bread()
           End If
       Return TryCast(Me.Session("BreadQuestionnaire"),Bread)
      End Get
End Property

The issue I have is as follows:

  • Staying on the page, when I enter the property for the first time the check to see if the session exists returns true and the session variable is never created
  • This then causes me an issue as I am then not able to set a value for the session based upon that object
  • I have also noticed that playing around on the page that the session is not being held on post back when I just set a session on the page.

Can anyone please help?

Try this:

Public ReadOnly BreadQuestionnaire as Bread 
                          Implements IQuestionnaire.BreadQuestionnaire
       Get
           Dim obj = TryCastMe.Session("BreadQuestionnaire"), Bread)
           If (obj IsNot Nothing) Then
              obj = new Bread()
              Me.Session("BreadQuestionnaire") = obj
           End If

           return obj
      End Get
End Property

Anytime you change a property on the bread object, you have to restore that object with the new property value in session. Session does not get updated when you update the property. So you'll need a setter to to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM