Introduction
For those ASP developers who are new to ASP.NET:
I am not going in detail about the Response.Redirect
or Session variables because they both are the same like classic ASP. This article is for those developers who used POST method of Form
in ASP to pass the Form variables from one page to another. Surprisingly, in ASP.NET, we cannot pass the Form variables from one page to another by posting or submitting the form using a submit button. I found out a little bit stranded at first. But soon I found out this new method of passing Form variables. (Who wants the old form submission now.)
The method of doing it
This is a bit complex but classy method of passing values across pages. Here, we expose the values we want to access in other pages as properties of the Page
class. Here, we code extra properties that we want to access in another web form. However, the efforts are worth considering. This method is object oriented than earlier methods. The entire process works as follows:
- Create the web form with controls that carry values.
- Create property with
Get
procedures to return the values in the controls.
- Provide some button that posts the Form to another WebForm.
- In the button click event handler, call
Server.Transfer
method that will transfer execution to the specified WebForm.
- In the second Form, you can get a reference to the first Form instance by using
ontext.Handler
property and cast it to the source WebForm class.
Then, you will use the Get
properties we created to access the control values.
Create a WebForm as shown below:
Write properties to access the values in the controls inside the source Page
class:
public string Name
{
get{return txtName.Text;}
}
public string Email
{
get{return txtEmail.Text;}
}
public string Phone
{
get{return txtPhone.Text;}
}
On the button click event, write code:
private void btnSubmit_Click(object sender, System.EventArgs e)
{
Server.Transfer("destination.aspx");
}
On the Page_Load
of the destination Page
, write the following code to access the public properties:
SourcePage pgSource;
pgSource= (SourcePage) Context.Handler;
Response.Write(pgSource.Name + "<br>");
Response.Write(pgSource.Email + "<br>");
Response.Write(pgSource.Phone + "<br>");
History