At times we need to pass some values across pages in our application. Now, as commonly known, HTTP is based upon stateless protocol, it can’t remember status of the past requests. So we have to explicitly manage state of the page. There are various Client side state management as well as server side state management techniques for managing state of the requests. Client side state management techniques (Viewstate, Clientstate, Hiddenfield, Cookies) are suitable if you are staying in the same page(except cookies which store some information in client browser). But when you want to pass values from one page to another here are some of the ways which can help.
I. Using Server.Transfer()
When we redirect any page using Server.Transfer() we ask the server to change only the control of the page from one page to another. So in that case we can get the previous page controls values.
protected void btnAdd_Click(object sender, EventArgs e) { Server.Transfer("SendInfo.aspx",true); }
The second parameter denotes weather to persist the current control state or not. II. Using PostBackUrl property
Another way of passing information easily by using the “PostBackUrl” property of the button control. This property used to post to a different page.
X [The page should be present inside the same application. you can't use this property like below X []
Track previous page
In the destination page we can track previous page and values of the controls like below.
Page prevPage = Page.PreviousPage; if (prevPage != null) { // Write your code logic }
Complete Code Block
The Complete Code Block may look like this.
First.aspx ---------- First.aspx.cs ---------- protected void btnPost1_Click(object sender, EventArgs e) { txtPostData.Text = "A Acharya"; Server.Transfer("sendInfo2.aspx",true); } protected void btnPost2_Click(object sender, EventArgs e) { txtPostData.Text = "A Acharya"; } NextPage.aspx.cs ---------- protected void Page_Load(object sender, EventArgs e) { Page prevPage = Page.PreviousPage; if (prevPage != null) { TextBox txtPrevPageName = (TextBox)prevPage.FindControl("txtPostData"); if (txtPrevPageName != null) { Response.Write(txtPrevPageName.Text); } } }
[PostBackUrl property depends upon javascript. So it will not work properly if javascript is disabled in the browser.]