ASP.Net: Transfering data between pages.

[I hope that I don't drive my readers crazy.  I'd love to settle on 1 topic and become an expert in that oen topic.  I just have way too many interests right now]

As I have coded web apps (in both ASP and ASP.Net as well as JSP) over the last 6 or 7 years (wow, it's been that long), I have had a recurring problem.  How do I transfer data between pages?

Initially my answer was what a lot of us do.  I simply put the data in the QueryString.  It's very easy and you can easily retrieve it.  The only problem of course (that I discovered through someone else's err) is that power users quickly realize that by messing with values in the querystring they can get the page to potentially do different things (especially if you've forgotten to add necessary checks).  This post here on The Daily WTF. Needless to say be cautious of QueryStrings and if you can avoid them then definitely avoid them.

After realizing what kinds of problems can happen I chose a different route.  I build a small form with nothing but hidden fields and I post the form to the new page (usually through a javascript).  The values are hidden in the form, so this seems like a good solution, but hold on... This is a good solution but it is definitely not a secure one.  Form posts can be spoofed (it's never happened to me, but I've become aware of the fact that form posts have issues.

So now what can we do?  I've heard people mention session. But cluttering session just sounds like a bad idea to me. 

The answer that I have come up with is the app cache.  It's perfect.  Data never touches the client's machine.  The only piece of information that the client touches is the the session id (which I combine with a “ket“ to create the cache's key).  Cache can be set to timeout, so you're not waiting until session times out -- you can safely time out the information sooner because it is only for a page transfer.  The only place this wouldn't work is if you're in a multi-server environment and you're not using sticky sessions.

Anyway, here's the code I wrote for this (it handles the adding of the Session ID to yor keys) [edited the code because Dave --a different one than the one I normally write about-- pointed out that I forgot the type on the first constant which is absolutely necessary]:

' Timeout for data being transfered is 2 minutes
Protected Const PAGE_XFER_CACHE_TIMEOUT_IN_MINUTES As Integer = 2


' Remove a key from the transfer cache

Public
Function removeKeyFromContext(ByVal key As String) As String
    context.Cache.Remove(key + Session.SessionID) 
End Function

' Check if a particular key exists in the transfer cache
Public
Function existsInContext(ByVal key As String) As Boolean 
    Return (Not (context.Cache(key + Session.SessionID) Is Nothing) AndAlso _
            Len(
CStr(context.Cache(key + Session.SessionID))) > 0)
End Function

' Reads a key back from the transfer cache
Public
Function readFromContext(ByVal key As String) As String 
      Dim __InContext As Boolean = existsInContext(key)
      If __InContext = False Then Return ""
      ' [ As my mom says “Some days I do better than others.. some more bad code,
      '   but I think this is the last of it]
      '
If __InContext Then
      '  Context.Items.Add(key, _
      '         Server.UrlEncode(
CStr(context.Cache(key + Session.SessionID).ToString))) 
      'End If

      Return Server.UrlDecode(Context.Cache(key + Session.SessionID).ToString)  
End Function

' Writes data with a key to the Transfer Cache
Public
Sub writeVarToContext(ByVal key As String, ByVal value As Object) 
    If existsInContext(key) Then removeKeyFromContext(key) ' [fixed this line of code]
    context.Cache.Add(key + Session.SessionID, _
                      value,
Nothing, Date.MaxValue, _
                      System.TimeSpan.FromMinutes(PAGE_XFER_CACHE_TIMEOUT_IN_MINUTES), _
                      CacheItemPriority.Default,
Nothing)
End Sub

 

There you go.  Let me know what you guys think.

Print | posted on Saturday, July 24, 2004 4:14 PM

Feedback

# re: ASP.Net: Transfering data between pages.

left by at 7/24/2004 11:48 PM Gravatar

"Protected Const PAGE_XFER_CACHE_TIMEOUT_IN_MINUTES = 2"

<br>

<br>This line should be declared instead as &quot;Protected Const PAGE_XFER_CACHE_TIMEOUT_IN_MINUTES As Integer = 2&quot;

<br>

<br>Your version declares the constant as an Object, which is obviously not what you want. I've found this mistake is made by a lot of VB6 programmers going to .NET (not that you're a typical VB6 programmer). Anyway, sorry, I couldn't help myself. I shifted into code review mode :-)

<br>

# re: ASP.Net: Transfering data between pages.

left by at 7/25/2004 4:31 AM Gravatar

Yeah... I added that at he last minute... I actually have 1 class that holds nothing but hold Constants (and I didn't have the class handy), and I was in a hurry to publich the code.

<br>

<br>Thanks for the catch...

# Some fun with my mistake...

left by at 7/26/2004 10:49 AM Gravatar

Some fun with my mistake...

# re: ASP.Net: Transfering data between pages.

left by at 8/15/2004 8:56 PM Gravatar

hi, i  tried to understand how this is but im having trouble.i guess its obviouse im new to all of this its a lot to take in. but i need to make sure i dont tranfer my stuff accidently . will you help me please. what you have seems very uesful. iwould very much appreciate it.    please dont leave me hanging out there.

<br>i wish to here from you soon. this is very important to me. thanks,  tif

# re: ASP.Net: Transfering data between pages.

left by at 8/16/2004 6:22 AM Gravatar

Tiffany,

<br>

<br>The functions above are a framework for you to use.  You'll want to put this stuff in a parent page class and then inherit all your pages from this parent page class (click on the &quot;Adventures in OOP&quot; link on the left if none of this makes sense... hopefully I've done a good job of describing OOP).

<br>

<br>Anyway once you have these functions in every page what you do is :

<br>

<br>From the first page -

<br>1) call &lt;b&gt;writeVarToContext&lt;/b&gt; to put your variables in the cache.

<br>2) then simply do a response.redirect to the new page

<br>

<br>On the new page:

<br>1)  Create class level variables for each of the values you are  passing

<br>2) In the page load event, check to see if a postback occurred; if not then simply check to see if the &lt;b&gt;existsInContext&lt;/b&gt; function returns true for each value

<br>3) if it does return true then simply call &lt;b&gt;readFromContext&lt;/b&gt; to read back in your values

<br>

<br>The code for the first page will look something like this:&lt;br&gt;

<br>&lt;i&gt;writeVarToContext(&quot;thisID&quot;, id) 'it is assumed that ID has a value&lt;br&gt;

<br>Response.Redirect(&quot;page2.aspx&quot;)&lt;/i&gt;&lt;br&gt;

<br>

<br>The code for the second page will look something like this:

<br>&lt;i&gt;Class Page2&lt;br&gt;

<br>  Inherits myBasePageClassThatContainsTheFunctions

<br>&lt;br&gt;

<br>  Protected _id as Integer&lt;br&gt;

<br>&lt;br&gt;

<br>  Protected Sub Page_Load(...) Implements Page.Load ' I'm not sure of the load event's signature (off the top of my head)&lt;br&gt;

<br>    If not isPostBack() Then&lt;br&gt;

<br>      _id = CInt(readFromContext(&quot;thisID&quot;))&lt;br&gt;

<br>    End If&lt;br&gt;

<br>  End Sub&lt;br&gt;

<br>Response.Redirect(&quot;page2.aspx&quot;)&lt;/i&gt;&lt;br&gt;

<br>&lt;br&gt;

<br>I hope that helps

# re: ASP.Net: Transfering data between pages.

left by at 8/16/2004 6:23 AM Gravatar

Sorry for the extraneous HTML... I really wish the comment thing would let me write HTML!

# re: ASP.Net: Transfering data between pages.

left by at 10/15/2004 12:28 AM Gravatar

re: ASP.Net: Transfering data between pages.

# How to a call a public function from a child page ?

left by at 2/9/2005 8:20 AM Gravatar

Hi,

<br>

<br>I want to call a public function from a child page.

<br>

<br>Sample:

<br>

<br>Page 1 &quot;Dad&quot;

<br>---------------

<br>

<br>public function hi()

<br>  response.write (&quot;ok&quot;)

<br>End Sub

<br>

<br>

<br>Page 2 &quot;Child&quot; (make with open.window from &quot;Dad&quot;)

<br>---------------

<br>call public function hi()

<br>

<br>'public function has to call from page 2 and write &quot;ok&quot; on page 1

<br>

<br>

<br>Thanks,

<br>C&#233;sar

<br>

# re: ASP.Net: Transfering data between pages.

left by at 8/9/2005 1:51 AM Gravatar

Thank you for this method, it was exactly what I needed.

I did find one problem with it though and I'm not entirely sure that it isn't simply because of how my asp.net app is running; a distinct possibility.

Anyway, I found that the session.sessionid parameter did not stay consistent between pages, or even between refresh. In order to get around this I monopolized on the User.Idenity object and used the login name to distinguish keys.

It's a hack, since if a single user has more than one window open variables could get mixed up and funky funness wouldl ensue.

As a side note, would anyone happen to know offhand why my session.sessionid values wouldn't stay conssitent?

Comments have been closed on this topic.