3

I have created a public property on my ASP.Net which holds a session of an entity. The purpose of which is that the entity is added to as the user fills in a number of steps on a form and then the whole lot is then saved to the database. However, when I go to use the session I am getting the error "object reference not set to an instance of an object".

Here is my code:

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

It is based upon code that I used in C# which has never given me any trouble before, but I have had VB.Net thrusted on me.

So, can anyone help me?

tereško
  • 58,060
  • 25
  • 98
  • 150
Andy5
  • 2,319
  • 11
  • 45
  • 91
  • 1
    In *which* method of the page the `BreadQuestionnaire` is called? – KV Prajapati Oct 04 '12 at 10:07
  • It is in the controller class in my mvc web app through the interface for the view – Andy5 Oct 04 '12 at 10:17
  • Here are a link about this issue - http://stackoverflow.com/questions/759795/c-sharp-cannot-check-session-exists – Wade73 Oct 04 '12 at 11:21
  • I am not using the Microsoft MVC template. So I am not using Action. It is more MVP than MVC. I have never had this problem with C#, but it seems a right old pain in VB.Net – Andy5 Oct 04 '12 at 12:12
  • The problem seems to be that when the public property is called the session is not being created. Keeping in the ASP.Net page I called the public property and it was nothing! – Andy5 Oct 04 '12 at 12:30

1 Answers1

0

system.web.httpcontext.current.session.add("BreadQuestionnaire", Bread)

I'm not certain me.session will work - does the property belong to the page class or is it in it's own? Either way using httpcontext.current should always be available.

And you're retrieving the session twice, you could do it in one trip:

Public ReadOnly BreadQuestionnaire as Bread 
                          Implements IQuestionnaire.BreadQuestionnaire
       Get
           Dim _sessionBread = system.web.httpcontext.current.session("BreadQuestionnaire")
           If_sessionBread Is Nothing Then
             Dim _bread As New Bread
             system.web.httpcontext.current.session.add("BreadQuestionnaire", _bread)
             Return _bread
           Else
           Return _sessionBread
           End If
      End Get
End Property
GJKH
  • 1,715
  • 13
  • 30