How to Pass or Transfer Data or Parameters values from one Aspx page to another Aspx page in Asp.Net C# VB.Net

Original Post: http://codedisplay.com/how-to-pass-or-transfer-data-or-parameters-values-from-one-aspx-page-to-another-aspx-page-in-asp-net-c-vb-net/ and http://www.codeproject.com/Articles/8055/Transferring-page-values-to-another-page

Pass or Transfer data from one page to another page is a very common task in Web development. Specially when you develop a project, for redirects or navigates from one ASP.NET Web page to another, you will frequently need to pass information from the source page to the target page or destination page. In this post, I will show you some ways of transferring data or parameters values between one page to another page which is termed as State Management. The pages I created to show you the example is really simple which consists of a text field and a button in the first page named as page1 and a blank second page named as page2.

According to the characteristics of aspx page lifecycle, web form do not retain their value after a page is displayed. To resolve this problem, ASP.NET provides the following ways to retain variables between pages:

1. Query Strings
2. Cookies
3. Session variables
4. Server.Transfer
5. Post Back URL

Let we have two aspx page named page1.aspx(contains txtName TextBox, txtAge TextBox & cmdTransfer Command Button) & a blank page2.aspx

Using Query String to Transfer Data:
The most common & easiest way of passing data is query string. Usually we pass value(s) through query string of the page and then this value is pulled from Request object in another page. One thing keep in mind that user can view query string value any time(from browser address, View source, even on mouse over of a link etc.). So never pass information which is secure like password through query string. Query string appear after a question mark of a hyperlink & you can add more by adding “&” Like:

Below is an example:
Suppose you want to pass the txtName TextBox value from page1 to page2 on cmdTransfer button click event then:
C# Code:

1
2
3
4
protected void cmdTransfer_Click(object sender, EventArgs e)
{
    Response.Redirect("page2.aspx?myname=" + txtName.Text);
}

VB.Net Code:

1
2
3
Protected Sub cmdTransfer_Click(sender As Object, e As EventArgs)
    Response.Redirect("page2.aspx?myname=" + txtName.Text)
End Sub

Now the question is how we can read/retrieve my name from page2.aspx page? The way is:
C# Code:

1
string myname = Request.QueryString["myname"];

VB.Net Code:

1
Dim myname As String = Request.QueryString("myname")

Now a bit advance, if you want to transfer special characters or a line with spaces then you must have to use Server.UrlEncode method before transfer and Server.UrlDecode method to read data from page2.aspx:

C# Code:

1
2
3
4
protected void cmdTransfer_Click(object sender, EventArgs e)
{
    Response.Redirect("page2.aspx?myname=" + Server.UrlEncode(txtName.Text));
}

VB.Net Code:

1
2
3
Protected Sub cmdTransfer_Click(sender As Object, e As EventArgs)
    Response.Redirect("page2.aspx?myname=" & Server.UrlEncode(txtName.Text))
End Sub

And to read from page2:
C# Code:

1
string myname = Server.UrlDecode(Request.QueryString["myname"]);

VB.Net Code:

1
Dim myname As String = Server.UrlDecode(Request.QueryString("myname"))

Now i want to show you how you can transfer more data:
C# Code:

1
2
3
4
protected void cmdTransfer_Click(object sender, EventArgs e)
{
    Response.Redirect("page2.aspx?myname="+Server.UrlEncode(txtName.Text)+"&myage="+txtAge.Text);
}

VB.Net Code:

1
2
3
Protected Sub cmdTransfer_Click(sender As Object, e As EventArgs)
    Response.Redirect(("page2.aspx?myname=" & Server.UrlEncode(txtName.Text) & "&myage=") + txtAge.Text)
End Sub

Now read both name & age from page2 in the same way:
C# Code:

1
2
string myname = Request.QueryString["myname"];
string myage = Request.QueryString["myage"];

VB.Net Code:

1
2
Dim myname As String = Request.QueryString("myname")
Dim myage As String = Request.QueryString("myage")

Now i want to show you how you can detect does a parameter contains value or not. So we have to modify read data section in page2 in the following way:

C# Code:

1
2
3
string myname ="";
if (Request["myname"] != null)
    myname = Request.QueryString["myname"];

VB.Net Code:

1
2
3
4
Dim myname As String = ""
If Request("myname") IsNot Nothing Then
    myname = Request.QueryString("myname")
End If

Using Cookie to Transfer Data:
Developers use cookies to store small amounts of information on the client. But keep in mind that user may refuse cookies, so you have to handle it. Finally I can say cookies are created on the server side but saved on the client side.

Example:
Now we create a cookie from page1 and read from page2:
For page1 button click event:

C# Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protected void cmdTransfer_Click(object sender, EventArgs e)
{
    if(Request.Browser.Cookies) // To check that the browser support cookies
    {
        HttpCookie cookie = new HttpCookie("myname");
        cookie.Value = txtName.Text;
        cookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(cookie);
        Response.Redirect("page2.aspx");
    }
    else
    {
        // You have to follow other option.
    }
}

VB.Net Code:

1
2
3
4
5
6
7
8
9
10
11
12
Protected Sub cmdTransfer_Click(sender As Object, e As EventArgs)
    If Request.Browser.Cookies Then
        ' To check that the browser support cookies
        Dim cookie As New HttpCookie("myname")
        cookie.Value = txtName.Text
        cookie.Expires = DateTime.Now.AddDays(1)
        Response.Cookies.Add(cookie)
        Response.Redirect("page2.aspx")
    Else
            ' You have to follow other option.
    End If
End Sub

Now read cookies from page2:
C# Code:

1
2
if(Request.Cookies["myname"] != null)
    Response.Write(Request.Cookies["myname"].Value);

VB.Net Code:

1
2
3
If Request.Cookies("myname") IsNot Nothing Then
    Response.Write(Request.Cookies("myname").Value)
End If

Using Session Variable to Transfer Data:
By default, session variables are stored in the web server’s memory. Session variables are unique per each user. If you open same url in two browser then server will create two independent sessions for you. Keep in mind that each session has a expire time. You can configure session time from IIS. Also one another thing is, you can receive session value form any pages after assigning. Write the below code under page1 button click event:

C# Code:

1
2
3
4
5
protected void cmdTransfer_Click(object sender, EventArgs e)
{
    Session["myname"] = txtName.Text;
    Response.Redirect("page2.aspx");
}

VB.Net Code:

1
2
3
4
Protected Sub cmdTransfer_Click(sender As Object, e As EventArgs)
    Session("myname") = txtName.Text
    Response.Redirect("page2.aspx")
End Sub

Now read session variable value from page2:
C# COde:

1
2
3
string myname ="";
if(Session["myname"]!=null)
    myname=Session["myname"].ToString();

VB.Net Code:

1
2
3
4
Dim myname As String = ""
If Session("myname") IsNot Nothing Then
    myname = Session("myname").ToString()
End If

Using Server.Transfer to Transfer Data:
We will use Server.Transfer to send the control to a new page. Note that Server.Transfer only transfers the control to the new page and does not redirect the browser to it, which means you will see the address of the old page in your URL. If the user clicks Refresh on his browser, the browser prompt a message warning that the page can not be refreshed without re sending information. Write the below code under page1 button click event:

C# Code:

1
2
3
4
protected void cmdTransfer_Click(object sender, EventArgs e)
{
    Server.Transfer("page2.aspx", true);
}

VB.Net Code:

1
2
3
Protected Sub cmdTransfer_Click(sender As Object, e As EventArgs)
    Server.Transfer("page2.aspx", True)
End Sub

And write the below code in page2 load event:
C# Code:

1
2
if (Request.Form["txtEmail"])
    Response.Write(Request.Form["txtNamel"]);

VB.Net Code:

1
2
3
If Request.Form("txtEmail") Then
    Response.Write(Request.Form("txtNamel"))
End If

Now run the page1, enter your name & click. You will see your name in page2.

Using Post Back URL to Transfer Data:
ASP.NET 2.0 has been introduced Cross page posting. By PreviousPage object you can search controls value from which page you are redirected here. To implement Cross page posting you have to define the PostBackUrl property of page1 button to page2. Like:

1
<asp:Button id="cmdTransfer" runat="server" Text="Transfer" PostBackUrl="page2.aspx"/>

Now write the below code in page2 load event:
C# Code:

1
2
TextBox txtName = (TextBox)(PreviousPage.FindControl("txtName"));
string myname =txtName.Text;

VB.Net Code:

1
2
Dim txtName As TextBox = DirectCast(PreviousPage.FindControl("txtName"), TextBox)
Dim myname As String = txtName.Text

So keep experimenting.

Difference Between Server.Transfer and Response.Redirect Asp.Net Interview Question

There is a common question for developers in Asp.net interview board that “What is the difference between Response.Redirect and Server.Transfer“. In a common term we can use both to redirect the user from source page to destination page. But there are some differences in between Response.Redirect and Server.Transfer, which i want to share with you.

Response.Redirect:
1. A round trip occurs to the client before loading the destination page, which means after redirecting a page from source page to destination page a round trip occur into the client to update the address bar and history of the client browser. And also the destination page will be loaded by initiating a new request which is the 2nd request to the server.
2. To pass data in this mechanism you can easily use Query String or Session value.

Server.Transfer:
1.It is a single request from source page to destination page. The destination.aspx will be loaded from the server without a 2nd request. Means it will not update the address bar and history of the browser.
2. You will get better performance.
3. You cannot use Query String.
4. To pass data between souce.aspx page to destination.aspx by using HttpContext object.
5. You can also use session object to transfer data.
6. Users can not bookmark the destination.aspx page.

Difference Between GET and Post HTTP Methods Asp.Net Interview Question

Might be this is the first interview question by the viva board. Which is very basic and you have to explain clearly. That’s why i am trying to write the post “Basic difference between GET and POST method”. In general view basically both method is used for submitting data into server. Please find the differences from below:

Submit Mechanism:
1. GET request is sent via URL.
2. Post request is sent via HTTP request body or you can say internally.

Get Method Indication:
Get_Post_Difference

Sample Code:

1
2
3
4
5
6
7
8
9
<html>
<body>
<Form method="GET" Action="http://search.yahoo.com/bin/search">
Name:
<input type="Text" name="Name" />
<input type="submit" value="Check" />
</Form>
</body>
</html>

Form Default Method:
1. GET request is the default method.
2. You have to specify POST method within form tag like <Form method=”POST”…….

Security:
1. Since GET request is sent via URL, so that we can not use this method for sensitive data data.
2. Since Post request encapsulated name pair values in HTTP request body, so that we can submit sensitive data through POST method.

Length:
1. GET request has a limitation on its length. The good practice is never allow more than 255 characters.
2. POST request has no major limitation. Read discussion part later of this article.

Caching or Bookmarking:
1. GET request will be better for caching and bookmarking.
2. POST request has not.

SEO:
1. GET request is SEO friendly.
2. POST request has not.

Data Type:
1. GET request always submitted data as TEXT.
2. POST request has no restriction.

Best Example:
1. SEARCH will be the best example for GET request.
2. LOGIN will be the best example for POST request.

HTTP Request Message Format:
GET:

1
2
3
4
GET /path/file.html?SearchText=Interview_Question HTTP/1.0
From: shawpnendu@gmail.com
User-Agent: HTTPTool/1.0
[blank line here]

POST:

1
2
3
4
5
6
7
POST /path/script.cgi HTTP/1.0
From: shawpnendu@gmail.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 8
Code=132

Some comments on the limit on QueryString / GET / URL parameters Length:
1. 255 bytes length is fine, because some older browser may not support more than that.
2. Opera supports ~4050 characters.
3. IE 4.0+ supports exactly 2083 characters.
4. Netscape 3 -> 4.78 support up to 8192 characters.
5. There is no limit on the number of parameters on a URL, but only on the length.
6. The number of characters will be significantly reduced if you have special characters like spaces that need to be URLEncoded (e.g. converted to the ‘%20′).
7. If you are closer to the length limit better use POST method instead of GET method.

Transferring page values to another page

http://www.codeproject.com/Articles/8055/Transferring-page-values-to-another-page

Sample screenshot

Introduction

We always come into situations in which we need to transfer values from one page to another page. In this article, I will show you some ways of transferring values from page to page. The page I created in this example is really simple which consists of a text field and a few buttons. The data entered in the text field will be transferred to another page by using different methods labeled on the buttons.

Using the code

Response.Redirect

Let’s first see how to transfer using Response.Redirect method. This maybe the easiest of them all. You start by writing some data in the text field, and when you finish writing the data, you press the button labeled ‘Reponse.Redirect’. One tip that I would like to share with you is, sometimes we want to transfer to another page inside the catch exception, meaning exception is caught and we want to transfer to another page. If you try to do this, it may give you a System.Threading exception. This exception is raised because you are transferring to another page leaving behind the thread running. You can solve this problem using:

Response.Redirect("WebForm5.aspx",false);

This tells the compiler to go to page “WebForm5.aspx”, and “false” here means that don’t end what you were doing on the current page. You should also look at the System.Threading class for threading issues. Below, you can see the C# code of the button event. “txtName” is the name of the text field whose value is being transferred to a page called “WebForm5.aspx“. “Name” which is just after “?” sign is just a temporary response variable which will hold the value of the text box.

private void Button1_Click(object sender, System.EventArgs e)
{
    // Value sent using HttpResponse
    Response.Redirect("WebForm5.aspx?Name="+txtName.Text);
}

Okay, up till this point, you have send the values using Response. But now, where do I collect the values, so in the “WebForm5.aspxpage_Load event, write this code. First, we check that the value entered is not null. If it’s not, then we simply display the value on the page using a Label control. Note: When you use Response.Redirect method to pass the values, all the values are visible in the URL of the browser. You should never pass credit card numbers and confidential information via Response.Redirect.

if (Request.QueryString["Name"]!= null)
    Label3.Text = Request.QueryString["Name"];

Cookies

Next up is cookies. Cookies are created on the server side but saved on the client side. In the button click event of ‘Cookies’, write this code:

HttpCookie cName = new HttpCookie("Name");
cName.Value = txtName.Text; 
Response.Cookies.Add(cName); 
Response.Redirect("WebForm5.aspx");

First, we create a cookie named “cName“. Since one cookie instance can hold many values, we tell the compiler that this cookie will hold “Name” value. We assign to it the value of the TextBox and finally add it in the Response stream, and sent it to the other page using Response.Redirect method.

Let’s see here how we can get the value of the cookie which is sent by one page.

if (Request.Cookies["Name"] != null )
    Label3.Text = Request.Cookies["Name"].Value;

As you see, it’s exactly the same way as we did before, but now we are using Request.Cookies instead of Request.QueryString. Remember that some browsers don’t accept cookies.

Session Variables

Next we see the session variables which are handled by the server. Sessions are created as soon as the first response is being sent from the client to the server, and session ends when the user closes his browser window or some abnormal operation takes place. Here is how you can use session variables for transferring values. Below you can see a Session is created for the user and “Name” is the key, also known as the Session key, which is assigned the TextBox value.

// Session Created
Session["Name"] = txtName.Text; 
Response.Redirect("WebForm5.aspx");

// The code below shows how to get the session value.
// This code must be placed in other page.
if(Session["Name"] != null) 
    Label3.Text = Session["Name"].ToString();

Application Variables

Sometimes, we need to access a value from anywhere in our page. For that, you can use Application variables. Here is a small code that shows how to do that. Once you created and assigned the Application variable, you can retrieve its value anywhere in your application.

// This sets the value of the Application Variable
Application["Name"] = txtName.Text; 
Response.Redirect("WebForm5.aspx"); 

// This is how we retrieve the value of the Application Variable
if( Application["Name"] != null ) 
    Label3.Text = Application["Name"].ToString();

HttpContext

You can also use HttpContext to retrieve values from pages. The values are retrieved using properties or methods. It’s a good idea to use properties since they are easier to code and modify. In your first page, make a property that returns the value of the TextBox.

public string GetName
{ 
    get { return txtName.Text; }
}

We will use Server.Transfer to send the control to a new page. Note that Server.Transfer only transfers the control to the new page and does not redirect the browser to it, which means you will see the address of the old page in your URL. Simply add the following line of code in ‘Server.Transfer’ button click event:

Server.Transfer("WebForm5.aspx");

Now, let’s go to the page where the values are being transferred, which in this case is “webForm5.aspx“.

// You can declare this Globally or in any event you like
WebForm4 w;

// Gets the Page.Context which is Associated with this page 
w = (WebForm4)Context.Handler;
// Assign the Label control with the property "GetName" which returns string
Label3.Text = w.GetName;

Special Note

As you see, there are various method in transferring values from one page to another. Each method has its own advantage and disadvantage. So, when you are transferring values, do your homework so that you have a better idea which approach is most feasible for you.

Advertisements

4 thoughts on “How to Pass or Transfer Data or Parameters values from one Aspx page to another Aspx page in Asp.Net C# VB.Net

  1. Thank you for another informative web site. The place else may I get that kind
    of information written in such an ideal method? I have a mission that I’m
    simply now operating on, and I’ve been on the glance out
    for such information.

  2. I do not even understand how I ended up here, however I assumed this submit used to be great.
    I do not understand who you are but certainly you’re
    going to a well-known blogger if you happen to are not already.
    Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s