Tuesday, February 21, 2012

Transfer data between pages asp.net

Here are several approaches to transfer data between pages:

Query Strings: You can transfer data between pages with query strings. The data will be displayed in the URL as parameters. Sometimes you want to encode the parameters, which can be done with HttpServerUtility.UrlEncode or HttpUtility.UrlEncode.

For example:

In page1, you can transfer the data to another page by redirecting.

Response.Redirect("Page2.aspx?parameter=" + TextBox1.Text);
 In page2, you can use

QueryString["parameter"] to get the data from page1.

Cookies: Cookies can be stored on client side machines. If you do not set the cookie's expiration, the cookie will be created but will not be stored on the user's hard disk. Instead, the cookie will be maintained as part of the user's session information. When the user closes the browser or if the session times out, the cookie is discarded.

You can add cookies to the Response.Cookies collection in a couple of ways, the following example shows two methods:

Response.Cookies["userName"].Value = "mike";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);

You can get more details from this link: http://msdn.microsoft.com/en-us/library/aa289495.aspx .

Session Variables: A session is stored in the server memory and it is unique to a particular client.

For example:

Store the data into a session in Page1:
Session["userName"] = "mike";
Retrieve the data in Page2:


Server.Transfer sends all of the information that has been assembled for processing by one page to another page. The URL on IE won’t be changed.
For example:

In page1, you can use ‘transfer’ to send all of the information in page1 to page2.
Server.Transfer("Page2.aspx", true);
Then you can use the below codes in Page_Load to retrieve the value of TextBox1 from page 1.
You can get more information from this link: http://msdn.microsoft.com/en-us/library/ms525800.aspx and ASP.NET State Management Overview.

Related thread: http://forums.asp.net/t/1208146.aspx

No comments:

Post a Comment