Thursday, June 23, 2011

Really Simple (less known) way to post data between ASP.Net Pages

There are the common ways to keep State.  For instance you can use QueryStrings, ViewState, HiddenFields, PreviousPage, and PageHistory… But what about Context?

An instance of the Context Object is associated in the server with each individual page instance that is requested.  Items stored in the Context item are extremely short lived because it only exists while the page is being processed and rendered and then it is automatically purged from memory.  The beautiful part of it, is that the context object is available while transfering between pages. 
The trick is that you must use a Server.Transfer method to call the receiving page to keep context in scope.  If you use Response.Redirect, you are actually making two trips between server and client and context is purged on the second trip.  By adding to the context.Items collection you can transfer values in a key/value type system.

A distinct advantage the context.items method has over QueryStrings is that it can contain complete objects.  Therefore, you can pass an entire class through the context.items method.

The Originating Page

Context.Items.Add("someKey", someValue)
Server.Transfer("~/SomePage.aspx")

Here we are adding to the Items collection by calling the .Add method with a key/value association.  Obviously, the someKey represents the key name and someValue represents the value that we want to send to a different page.  We then call the Server.Transfer method which calls the page we want to send the values to.


The Recipient Page

Dim someString As String = Context.Items.Item("someKey").ToString()



Here we are dimensioning someString as a string and instantiating it by setting it to the value of the Items.Item in reference to someKey.


Conclusion


In conclusion, it is secure method (as context resides on the server) to move objects, strings, or values of any type between webpages in ASP.Net


Happy .Netting…Saleh

No comments:

Post a Comment