Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post May 02, 2012 05:20 AM by Allen Li - MSFT
Apr 30, 2012 05:43 PM|LINK
Can anybody shed some light on this problem?
I have an ASP.NET user control which generates an instance of an object that I need to save to use after each postback. I reckon saving to the Session object is the best bet for persistence, but this doesn't seem to be as straightforward as I was expecting.
I have concluded that the object is not being successfully saved into the Session object before the postback. Although no exception is produced, the session variable is not actually created, as after the postback, the key in question has disappeared. I am using
code along these (much simplified) lines, in a Load handler for the user control in question:
If Me.TreeSession Is Nothing Then
Me.TreeSession = Me.Session ' where Me is the user control
End If ' and TreeSession is UC property
If Not Page.IsPostBack Then
myfoobar = New Foobar()
Dim retrievedfb As Foobar = _
DirectCast(Me.TreeSession("Myfoobar"), Foobar) ' see /1/ below
If Not retrievedfb Is Nothing Then
myfoobar = retrievedfb
' and then later
The problematic symptom being that 'retrievedfb' at /1/ is always Nothing (i.e. null) at postback. After much research, I've tried very many possibly relevant approaches that seemed relevant for sorting this problem out, but haven't made much progress. My attempts
a) I have the Foobar class flagged with the Serializable attribute.
b) I tried investigating the use of Page.RegisterRequiresControlState for the user control, along with SaveControlState and LoadControlState handlers, but this approach seems to spiral out of control when applied to my user control (being as my UC contains
many other web controls and such like). Anyway, I don't think I want to be storing the state of the whole control, I just need to persist my Foobar instance into which I have 'set' the important data.
Does anybody know where I am going wrong? I seem to have run out of ideas, and I could do with a pointer in the right direction.
Thanks very much if you can advise!
Apr 30, 2012 06:44 PM|LINK
Try stuffing this into your Page_Load event.
For x = 0 To Session.Contents.Count - 1
Response.Write(Session.Contents.Keys(x) & " - ")
Response.Write(Session.Contents.Item(x) & "<br>")
This will display all session variables on your page so you can track them through your page lifecycle.
The way I've always done session variables is simply Session.Add("VarName", txtObject.Text) wrapped in a try/catch.
May 02, 2012 05:20 AM|LINK
Hi, please set breakpoints to your codes and check how your codes run. You can also refer to the following documents about how to use Session:
Additionally, in order to find the root cause of the issue, please paste more codes here for analysis.