May 7, 2014

In asp.net, Response.Redirect, PostBackUrl and Server.Transfer are similar but all of these are somewhat different. In this post, I will go through the differences of these three approaches.

Response.Redirect

This will cause the browser to load the specified page. The page may or may not be part of the existing application. This will result in a http get and the new page will not have access to any data on the current page. This can be triggered by any control that performs postback or even on Page_Load event.

Response.Redirect can be set in the following way.

  1. protected void b1_Click(object sender, EventArgs e)
  2. {
  3.     Response.Redirect("some page");
  4. }

 

PostBackUrl

PostBackUrl property can only be set on an asp.net button control. The UseSubmitBehavior property needs to be set to true. This will result in a http post and the new page can retrieve current page's data using Request.Form and Page.PreviousPage. The user will notice the change in the once the button is clicked. PostBackUrl can contain pages from current application or any other pages as well.

PostBackUrl is set in the following way.

  1. <asp:Button ID="b1" runat="server" Text="postback" PostBackUrl="~/PostBack2.aspx" UseSubmitBehavior="true" />

 

To retrieve data,

protected void Page_Load(object sender, EventArgs e)
{
    l1.Text = Request.Form["t1"];
    l1.Text += ((TextBox)this.PreviousPage.FindControl("t1")).Text;
}

Server.Transfer

Server.Transfer performs a http post and data can be obtained similar to PostBackUrl, that is, using both Request.Form and Page.PreviousPage. Server.Transfer can only transfer to a page in the current application. Also the url does not change in the browser. Like Response.Redirect, this can be triggered by any control that performs postback or even on Page_Load event.

Server.Transfer can be used in the following way.

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

To retrieve data,

protected void Page_Load(object sender, EventArgs e)
{
    l1.Text = Request.Form["t1"];
    l1.Text += ((TextBox)this.PreviousPage.FindControl("t1")).Text;
}

0 comments:

Reference: Shahed Kazi at AspNetify.com