Steve C. Orr

Software Engineer, Web Developer, Database Designer
 
  

 







Q: How do I pass values between pages?

A: Context and QueryString are common ways to pass values between pages in ASP.NET. Which one is best depends on the particular circumstances.

The QueryString has been a common way of passing data around the Internet since before ASP was even invented. Before a variable value is placed on the QueryString, it should be encoded to ensure problematic characters (such as spaces and symbols) are interpreted correctly as data:

'Page1.aspx appends the user’s name to the QueryString

Dim sName As String

sName = Server.UrlEncode(txtName.Text)

Response.Redirect("Page2.aspx?Value=" & sName)

 

'Page2.aspx parses the value from the QueryString

Dim sName As String

sName = Request.QueryString("Value")

Response.Write("Your name is " & sName)

When the user arrives at Page2, the data is appended to the URL. Therefore, the address listed in their browser will look something like this:

http://localhost/MyWebSite/MyPage.aspx?Value=Steve+Orr

The Context object isn’t as well known as the Session object, but it should be — the syntax is the same; simply replace the word “Session” with the word “Context”:

'Page1.aspx stores value in context before transferring

Context.Items("UserName") = txtName.Text

Server.Transfer("Page2.aspx")

 

'Page2.aspx retrieves the value from Page1’s context

Dim sName As String

sName = Context.Items("UserName").ToString

Response.Write("Your name is " & sName)

One of the main differences between Context and Session is that Context only stays in scope until the page is sent to the browser. Therefore, this is one of the few examples where Server.Transfer must be used instead of Response.Redirect. Because Response.Redirect would cause the context to go out of scope, the data would be lost. Context uses server memory more sparingly than Session variables, so it’s often preferable except in cases where data needs to be stored across the user’s entire visit.

Then & Now

Before ASP.NET 1.0, posting data from one page to another was comparable to the QueryString (aka “get”) technique. ASP.NET 1.x made this technique less practical than it used to be because there was no longer any simple way to post data from one page to another. The new philosophy was that pages were meant to post back to themselves.

As ASP.NET 2.0 comes into focus and frees us from most cross-page posting limitations, this technique starts to become more favorable again. For example, by setting the PostBackURL property of a button control on Page1.aspx, you can have it post all form values (including any hidden text fields) to Page2.aspx. This technique requires no server-side code in Page1.aspx:

'Page2.aspx retrieves the posted form value

Dim sName As String

sName = Request.Form(“TextBox1”).ToString

Response.Write("Your name is " & sName)


 

(advertisement)