Saturday, December 31, 2011

Ways to Transfer Data Between Asp.net Pages

Each button in the demo has the required code in it's Click event handler, and brings you to a separate target page that gets and displays the data that was sent. Here are the methods:

1. Use the querystring:

protected void QueryStringButton_Click(object sender, EventArgs e)
{
Response.Redirect("QueryStringPage.aspx?Data=" + Server.UrlEncode(DataToSendTextBox.Text));
}

2. Use HTTP POST:



protected void HttpPostButton_Click(object sender, EventArgs e)
{
// The PostBackUrl property of the Button takes care of where to send it!
}

3. Use Session State:

protected void SessionStateButton_Click(object sender, EventArgs e)
{
Session["Data"] = DataToSendTextBox.Text;
Response.Redirect("SessionStatePage.aspx");
}

4. Use public properties:

public string DataToSend
{
get
{
return DataToSendTextBox.Text;
}
}

protected void PublicPropertiesButton_Click(object sender, EventArgs e)
{
Server.Transfer("PublicPropertiesPage.aspx");
}

5. Use PreviousPage Control Info:

protected void ControlInfoButton_Click(object sender, EventArgs e)
{
Server.Transfer("ControlInfoPage.aspx");
}

// target page:
protected void Page_Load(object sender, EventArgs e)
{
var textbox = PreviousPage.FindControl("DataToSendTextbox") as TextBox;
if (textbox != null)
{
DataReceivedLabel.Text = textbox.Text;
}
}

6. Use HttpContext Items Collection:

protected void HttpContextButton_Click(object sender, EventArgs e)
{
HttpContext.Current.Items["data"] = DataToSendTextBox.Text;
Server.Transfer("HttpContextItemsPage.aspx");
}

// target page:
protected void Page_Load(object sender, EventArgs e)
{
this.DataReceivedLabel.Text =(String) HttpContext.Current.Items["data"];
}

7. Use Cookies:

protected void CookiesButton_Click(object sender, EventArgs e)
{
HttpCookie cook = new HttpCookie("data");
cook.Expires = DateTime.Now.AddDays(1);
cook.Value = DataToSendTextBox.Text;
Response.Cookies.Add(cook);
Response.Redirect("HttpCookiePage.aspx");
}

// target page:
protected void Page_Load(object sender, EventArgs e)
{
DataReceivedLabel.Text = Request.Cookies["data"].Value;
}

8. Use Cache:

protected void CacheButton_Click(object sender, EventArgs e)
{
Cache["data"] = DataToSendTextBox.Text;
Server.Transfer("CachePage.aspx");
}
// target page:
protected void Page_Load(object sender, EventArgs e)
{
this.DataReceivedLabel.Text = (string) Cache["data"];
}

Actually, there are a number of other methods. You can use a database, a Data Store such as Redis or BPlusTree, file storage, or even the Appdomain Cache. But as these are not as common, we'll leave those as an exercise for the reader. I should mention that the use of Cache and Application (not shown) are not user - specific, but they can easily be made so by prepending the key used with something unique to the user such as their SessionId.

Courtesy:Peter Bromberg