Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Intermediate
Feb 3, 2003

Passing values from a page to another by means of the Context object

Sometimes you may want to gather the user input with a page, and process it in a different page. As you know, ASP.NET web forms can post only to themselves, so you can't just change the form's <i>action</i> attribute and make the form post to a different page. And anyway, you may want to do some processing in the first page, and then pass the control to a second page to complete some operations. This second page will need a way to get the user input of the first page of course, so what can you do? The first and simplest solution is to use a direct Response.Redirect call and load the second page with all the required user input values in the querystring. However, this may not be possible if you have to pass a lot of data (the querystring's length is limited), and you may also want to pass already processed values, and you don't want the user to see them. A better and more elegant solution is to use the Items collection of the Contect object, that just allow to set and retrieve context-specific variables. In the first page, you set the context values as follows:

Context.Items("FirstName") = txtFirstName.Text
And then transfer the execution to the second page with:

In the second page you can retrieve the context variables as follows:

Dim firstName as String = CType(Context.Items("FirstName"), String)
This works fine, but if you have to pass many values you can also improve this technique. In the first page's code-behind class you can add public properties that expose the user input or other values that may result from your processing, and you set them just before transfering to the second page. Here's an example:

Public Class InputForm : Inherits System.Web.UI.Page
    Protected FirstName As System.Web.UI.WebControls.TextBox
    Protected LastName As System.Web.UI.WebControls.TextBox

    Public FirstNameValue As String = ""
    Public LastNameValue As String = ""

    Private Sub Finish_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs)
        FirstNameValue = FirstName.Text
        LastNameValue = LastName.Text
    End Sub
End Class
Then, in the second page you get a reference to the first page instance by casting the Context.Handler object to the type of the first page, and then you can read its custom properties. The following lines shows what to do:

Dim input As InputForm = CType(Context.Handler, InputForm)
Response.Write("First name: " & input.FirstNameValue)
Response.Write("Last name: " & input.LastNameValue)
Marco Bellinaso
Thanks for your registration, follow us on our social networks to keep up-to-date