ControlFreak
LANGUAGES:VB.NET | C#
ASP.NETVERSIONS: 1.x | 2.x
Data Passing Round-Up
Compare Techniques for Passing Data between Web Pages: WhichAre Best Under Diverse Circumstances?
By Steve C. Orr
One of the most commonly asked questions about ASP.NET ishow to pass values between pages. At first this may seem like a trivial task toa moderately experienced programmer ? but you?ll soon see that the subject isdeep and potentially complex. There are so many ways to achieve this goal thatfinding the optimal solution in any given scenario can be challenging. Conflictinggoals ? such as ease of development, usability, security, efficiency, datasize, and reliability ? can all influence your decision.
Application State
HttpApplicationState is a classic ASP object that servesas a great place to store global values or objects. For example, if you?ve gota fairly static DataSet that is used frequently, you might choose to store itin application state. Retrieving the object is then as simple as one line of code:
'VB.NET
Dim ds As DataSet = CType(Application(?MyDataSet?), DataSet)
//C#
DataSet Source = (DataSet)(Application[?MyDataSet?]);
Storing items in application state is nearly as easy asretrieving them. The main difference is that you need to lock the Applicationobject before storing a value, and unlock it when you?re finished. This helpsensure no nasty threading issues muck things up, such as two processes tryingto update the value at the same time. Instead, the processes will be queued, ifnecessary, to avoid deadlocks:
'VB.NET
Application.Lock()
Application("MyDataSet") = MyDataSet
Application.UnLock()
//C#
Application.Lock();
Application["MyDataSet"] = MyDataSet;
Application.UnLock();
Modifications to objects stored in application state are notpersisted automatically back into application state. In other words, if youmodify the DataSet after retrieving it from application state, you?ll probablywant to explicitly overwrite the old DataSet in application state with the newone using the code above.
As you might have guessed by the name, the Applicationobject is in scope only for the current Web application. In other words, if youhave two ASP.NET Web sites on your server, Application2 will not be able toread values from the Application object of Application1.
Cache Object
There is no debating the utility of the Applicationobject. However, its age is starting to show a bit ? and there?s a new objectin town: HttpCache.
Like the HttpApplicationState object, the HttpCache objectis a container useful for storing global variables and objects. At its simplest,the syntax is very similar to using the Application object, although no lockingor unlocking is necessary because thread management is built in to the object:
'VB.NET
Cache("MyGlobalValue") = TextBox1.Text 'Store
Dim s As String = Cache("MyGlobalValue").ToString'Retrieve
//C#
Cache["MyGlobalValue"] = TextBox1.Text; //Store
string s = Cache["MyGlobalValue"].ToString();//Retrieve
The Cache object has features that the Application objectdoesn?t. These features are all geared toward increasing scalability.
The Cache object implements moreintelligent storage techniques than the Application object. For example, itwill automatically remove seldom-used items from the Cache if memory starts toget low. Luckily, it is possible to optionally specify a priority for each itemin the cache ? so important items will be more likely to stick around. It isalso possible to be informed when an item is removed from the cache using theCacheItemRemovedCallback delegate.
The Cache object allows you to modify how objects arestored in the cache, and for how long. For example, you can specify that acache item expire after a certain amount of time (Sliding Expiration) or at aspecific, fixed time (Absolute Expiration).
The following code stores a value in the Cache object justlike the previous code; however, the item will expire (and be removed from thecache) after 20 minutes:
'VB.NET
Cache.Insert("MyGlobalValue", TextBox1.Text, _
Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration,_
New TimeSpan(0, 20, 0))
//C#
Cache.Insert("MyGlobalValue", TextBox1.Text,
null,System.Web.Caching.Cache.NoAbsoluteExpiration,
new TimeSpan(0, 20, 0));
The Cache object can also expireitems in response to other kinds of events. For example, cache items can bedependent upon a specific file. When the file changes, therelated cache item is removed. Cache items can also be dependent uponother cache items. Using this technique, when a parent cache item is removed,any related children are also automatically removed. The CacheDependency objectis the key to all of this. There is also a SqlCacheDependency object that canremove an item from the cache whenever specific data in a SQL Server databasechanges.
Like the Application object, the Cache object?s scope isglobal to the current Web application.
Session State
While the Application and Cache objects are great forstoring items globally, the Session object specializes in storing user-specificitems. The syntax is simple and familiar:
'VB.NET
Session("UserName") = TextBox1.Text 'Store
Dim s As String = Session("UserName").ToString'Retrieve
//C#
Session["UserName"] = TextBox1.Text; //Store
string s = Session["UserName"].ToString();//Retrieve
The Session object applies to the current Web applicationonly, and also applies only to the current user session. In other words, if twousers visit a site that implements the above code, their user names will bestored separately and they?ll never see each other?s user names.
The Session object is sure handy, butbeware of scalability problems. Like the Application and Cache objects, sessionitems are stored in server memory by default. However, the Session object canconsume memory far faster in situations where there are many users and/or manysession variables. If you store 10 session items per user and your site gets100 simultaneous users, there will be a total of 1,000 items in session state. Luckily,modern versions of ASP.NET provide reasonable ways to deal with this issue. Forexample, it is possible to configure an application (via the web.config file)to store session items in a SQL Server database, or on a specific serverdedicated to managing session data. If these don?t suit your needs, it is alsopossible to have session data stored in a custom storage provider of your owndesign.
Context
One of the lesser known techniques for passing databetween pages is the Context object. An instance of the context object isassociated with every page instance. Because a page generally only lives on theserver for milliseconds (while being executed and rendered), items stored inthe Context object are short lived. In many situations this is the mostefficient way to store items because they are quickly and automatically purgedfrom memory. In addition to living for the life of a page, the Context objectalso stays in memory while transferring to another page. The following code storesan item in Page1 and then retrieves the item in Page2, after which the Contextobject (and all items it contains) are cleared from server memory:
'VB.NET
Context.Items("UserName") = TextBox1.Text 'Page1
Server.Transfer("Page2.aspx") 'Page1
Dim s As String = Context.Items("UserName").ToString'Page2
//C#
Context.Items["UserName"] = TextBox1.Text; //Page1
Server.Transfer("Page2.aspx"); //Page1
string s = Context.Items["UserName"].ToString();//Page2
Note that Server.Transfer must be used here for thistechnique to work. Response.Redirect would fail because that makes a round tripto the client, which kills the instance of the Context object. Figure 1 detailssome of the side effects you may encounter.
| Response.Redirect | Server.Transfer |
| Allows redirection to any URL on any Web server. Data must be passed manually via QueryString or one of the other techniques mentioned in this article. Allows users to refresh and bookmark the page normally. Requires an extra round trip to the client, which is inefficient and can therefore hurt scalability. A classic, time-proven technique. | Can only transfer to pages in the same Web application. Allows use of the Context object to automatically pass values between pages. The client is never informed the URL has changed, which has several effects: - The browser address bar still (incorrectly) reflects the original page.
- Can cause problems when the user tries to refresh or bookmark the page.
- Can cause path mismatches when referring to images files, css files, etc.
- Can be useful for intentionally masking the true path of a page.
|
Figure 1:Response.Redirect and Server.Transfer both allow a new page to be sent to theuser, but which one is best depends on which pros and cons are most tolerablein a given situation.
Besides passing values between pages, the Context objectis also useful for a variety of other things. For example, if you?re calling acustom object from your page, that custom object can?t access the Applicationor Session objects directly unless they use the Context object to retrievethem:
Context.Session("Whatever")...
Advanced techniques are also possible, such as directlyreferring to public properties of the previous page instance.
ViewState
The ViewState object is useful for storing objects betweenpostbacks to the same page. It cannot be used for passing values to otherpages. The syntax is virtually identical to the Session object:
'VB.NET
ViewState("PageValue") = TextBox1.Text 'Store
Dim s As String = ViewState("PageValue").ToString'Retrieve
//C#
ViewState["PageValue"] = TextBox1.Text; //Store
string s = ViewState["PageValue"].ToString(); //Retrieve
Instead of being stored in server memory (like thepreviously mentioned techniques), ViewState items are encoded and output intothe generated HTML of the page. If you right click on an ASP.NET-generated Webpage in Internet Explorer and choose View Source, you?ll see an HTML elementthat looks a lot like this:
<input type="hidden" name="__VIEWSTATE"id="__VIEWSTATE"
value="/wEPDwUKMTkwNjc4NTIwMWRkv1e5TcWOq4qnwyDuryos="/>
When the page is posted back to the server, ASP.NET grabsthis garbled-looking value and decodes it back into its original state. Becareful, though. Although ViewState values are encoded, they are not encrypted.It may be possible for savvy users to decode ViewState values, so you shouldn?tstore sensitive data in ViewState.
You should also try to avoid storing large amounts of datain ViewState as it eats valuable bandwidth on its way to the client and back. Becauseof such concerns, it is possible to turn off ViewState for pages where it isnot needed or wanted. You should keep this in mind when developing controls,because they may not be able to use ViewState if they are hosted on a page thathas ViewState turned off. One solution is to use ASP.NET 2.0 ControlStateinstead of ViewState. ControlState is similar to ViewState but remains on allthe time, so it is useful for control development when you need to storecritical information between postbacks. It is recommended that ViewState shouldstill be used in control development for storing non-critical values betweenpostbacks.
QueryString
Passing data via QueryString is a classic, time-testedtechnique. Whenever you see a URL with question marks and ampersands and otherstrange values tacked on after the page name, you know a ?Get? is beingperformed to pass data along with the URL:
www.somesite.com/pg1.aspx?name=Bob&userid=9&clr=red
The QueryString portion of the URL begins at the questionmark (which is only necessary when passing data via QueryString). Each dataitem consists of a name/value pair. Every data item following the first onemust be separated by an ampersand (&). Some characters are not valid in aURL, so they must be encoded (usually using the Server.UrlEncode method):
'VB.NET
Dim s as string = Server.UrlEncode(TextBox1.Text) 'Page1
Response.Redirect("Page2.aspx?UserName=" & s)'Page1
Dim s2 As String = Request.QueryString("UserName")'Page2
//C#
string s = Server.UrlEncode(TextBox1.Text); //Page1
Response.Redirect("Page2.aspx?UserName=" + s); //Page1
string s2 = Request.QueryString["UserName"]; //Page2
Because QueryString values are visible to the user in theaddress bar of their browser, they are not in the slightest bit secure. Expectcurious people to tinker with them ? and be sure to put code in place to dealwith any resulting errors.
When a user bookmarks a URL into their browser favorites,the full URL (including any QueryString values) is saved and used again thenext time the user chooses it from their favorites. This could be a good thingor a bad thing, depending on what values are involved. It can be quite usefulfor a user to click on a favorite link and resume right where they left offwith all relevant data immediately available (since the data was in theQueryString). It can also be a pain to users when a URL they bookmarked doesn?twork anymore, simply because it contains stale QueryString data. Keep this inmind when developing with QueryStrings so you can give your users the bestpossible experience.
Because the QueryString can only contain text charactersit is only useful for storing simple data types, and is therefore less flexiblethan previously mentioned techniques (which can store virtually any kind ofobject). Also keep in mind that browsers impose size limits for URLs. Althoughthe limit varies from browser to browser, expect to run into problems if a URL(including its QueryString) reaches about 2,000 characters. Users don?t likeQueryStrings that are that long because they are ugly, confusing, and cumbersometo type in manually; try to limit usage of QueryStrings to situations thattruly benefit from them.
Cookies
Cookies are a small bit of text (no more than 4096 bytes)that are sent from the server and stored on the client. All relevant cookiesare automatically transferred back and forth between the client and server oneach page request, so server-side code can use them as needed. The syntax forbasic use is simple:
'VB.NET
Response.Cookies("myval").Value = TextBox1.Text 'Store
Response.Cookies("myval").Value 'Retrieve
//C#
Response.Cookies["myval"].Value = TextBox1.Text;//Store
Response.Cookies["myval"].Value; //Retrieve
Cookies can be customized in many ways, such as automaticexpiration, storing multiple values in a cookie, and limiting cookie scope tospecific domains and folders.
Because cookies are stored on the user?s hard drive, it ispossible for users to tamper with them. Therefore, sensitive data should not bestored in cookies. It?s also possible (and fairly common) for users to turn offcookie support in their browser as they?ve gotten a rather bad reputation forinvading privacy. (Because no errors are thrown in such a situation, the onlyway to detect this condition is to try to set a cookie and see if it?s stillthere after a postback.) Browsers also limit cookie usage in a variety of waysin an attempt to deal with privacy abuse. Because of these reasons I suggestavoiding cookies most of the time ? they simply aren?t reliable.
Post
In the days before ASP.NET, posting data was as common asthe QueryString (aka ?Get?) method for passing data between pages. However,when ASP.NET 1.x came along it was difficult for a page to post data to anotherpage. Instead, the ASP.NET 1.x model ordained that pages should post back onlyto themselves. ASP.NET 2.0 has freed us from this limitation. The Buttoncontrol now has a PostbackUrl property that can be used to specify that theform should be posted to a different page. By setting the PostbackUrl propertyof a button on Page1, the value of a page 1 textbox can be retrieved in page 2with this code:
Dim s As String = Request.Form("TextBox1").ToString'VB.NET
string s = Request.Form["TextBox1"].ToString(); //C#
You can also use hidden fields to pass around data thesame way. Data in hidden fields isn?t visible to the user unless they view thepage source. Data that is posted to the server (whether in a hidden field ornot) is susceptible to tampering; therefore, sensitive data should stay on theserver using one of the previously mentioned techniques.
Conclusion
There are other techniques for passing data between pages(see Figure 2). One approach is to store data in a database between pagerequests. I haven?t bothered to include sample code for this because the Internetis full of sample ADO.NET code that reads and writes to databases.
| Technique | Scope | Memory Consumption | Security |
| Application | Web application | Medium | Very secure |
| Cache | Web application | Medium | Very secure |
| Session | User session | Potentially High (Configurable) | Very secure |
| Context | Between two pages | Low | Very secure |
| ViewState | One page (stores between postbacks) | Potentially High | Medium |
| QueryString | Between two pages | Low | Low |
| Cookies | Per user, per computer, potentially infinite expiration | Low | Low |
| Post | Between two pages | Medium/Low | Low |
| Database | Customizable | Medium/High | Very secure |
Figure 2: Thereare a variety of techniques for passing values between pages. Which one is bestfor a particular situation depends on your needs.
AJAX is alsocoming on strong. I?m not sure I?d classify it as a way of passing data betweenpages, although it is certainly a nice, transparent way to send data back tothe server. Once it?s there you could easily use Session or Cache or most ofthe other techniques detailed in this article to store data, as necessary.
You should now have a reasonably deep understanding of thevarious techniques for passing data between pages. As you can see, there is nosingle technique that is best in all cases. The method that is best for a givensituation depends on many variables, such as scope, data size, security,usability, and scalability. Now that you know the details you can pickwhichever technique best meets your requirements.
SteveC. Orr is an ASPInsider, MCSD, Certified ScrumMaster, and a Microsoft MVPin ASP.NET. He?s been developing software solutions for leadingcompanies in the Seattle area formore than a decade. When he?s not busy designing software systems or writingabout them, he can often be found loitering at local user groups and habituallylurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.netor e-mail him at mailto:Steve@Orr.net.