Solve Postback Hassles with Cross-Page Postbacks in ASP.NET 2.0

Solve Postback Hassles with Cross-Page Postbacks in ASP.NET 2.0

y default, an ASP.NET web form posts back to itself whenever a postback operation occurs. That behavior wasn’t terribly common in web pages before ASP.NET appeared, and isn’t always what you want to have happen: What if you want to post a web form to another web page in the application? ASP.NET made that fairly difficult in ASP.NET 1.0, but ASP.NET 2.0 makes developers lives easier in this regard?by adding a new feature called “cross-page postbacks” that allows a web page to post its data back to a different web page. In cross-page postbacks, the page that initiates the postback is called the source page and the page to which the client posts is called the target page.

Conveniently, the target page can still retrieve any control values posted by the source web page in a cross-page postback operation. In other words, from a development point of view, you can process the posted data in much the same way you would process any normal ASP.NET postback.

The new feature means ASP.NET 2.0 developers now have three techniques for transferring processing from one web page to another in an application: Response.Redirect, Server.Transfer, and the new cross-page postback features. You’re probably familiar with the first two, so I’ll review them only briefly, and then concentrate on how to use the cross-page postback feature, showing how it works and how it differs from the Response.Redirect and Server.Transfer techniques.

The Response.Redirect Method
The Response.Redirect method is by far the simplest method of redirecting processing from a source page to a different destination or target page in the same or even across different applications. When the web server receives a request for redirection, it sends a response header to the client that causes the client to send a new request back to the server. In other words, a redirect causes two request/response cycles: one for the original and one for the new redirected request.

ASP.NET makes redirects easy. The following code snippet illustrates how to use the Response.Redirect method:

   protected void Redirect_Click(object sender, EventArgs e)   {      Response.Redirect("menu.aspx");   }

Note that the redirect request is a GET request, meaning that you can’t post data from the original page via the Response.Redirect command. You can work around that to pass data from the source to the target by using query strings in the Response.Redirect method call as shown below:

   protected void Redirect_Click(object sender, EventArgs e)   {      Response.Redirect("menu.aspx?userName=" + UserName.Text));   }

The preceding example passes a query string as a parameter to the Response.Redirect method along with the target URL. The target can now use code such as the following to retrieve the source’s data as shown below:

   protected void Page_Load(object sender, EventArgs e)   {      string userName = Request["userName"];      //Other code   }

The Server.Transfer Method
Instead of relying on the client to make a request to a new page, Server.Transfer is a server-side redirection technique that simply changes the code’s “focus” on the web server to a new page. Server.Transfer is far more efficient than Response.Redirect when the target page resides on the same web server, because it avoids the extra roundtrip and uses only server resources for the redirection. Note that it has a side effect?the URL shown in the web browser does not change either?meaning clients may think they posted their data to one page while actually posting it to a different page. In most cases, that’s not a problem, but it can make debugging more difficult.

Server.Transfer also preserves the HttpContext of the initiating page; therefore the target page can access the control values of the source page. Specifically, you can use the FormsCollection property to retrieve the source control values from the target page when using the Server.Transfer technique. First, make sure you use the overloaded Server.Transfer method, which accepts two parameters?the target URL, and a Boolean preserveForm value which tells the server to preserve the query string and any control values from the source page. Set the preserveForm parameter to true in the source web page as shown below:


Then, from the target page, to retrieve the value of a textbox control called txtUserName for example, use the following code:

   object obj = Request.Form["txtUserName"];

Response.Redirect vs. Server.Transfer
Because Response.Redirect requires an extra round trip, you should avoid it for high-volume web sites due to associated performance and scalability issues. However, this is the only technique that you can use to redirect from one web server to another. In contrast, Server.Transfer is more efficient, but can transfer execution only to a different web page on the same server. In essence, you’d use Server.Transfer to eliminate unnecessary roundtrips when both the source and the target web page reside on the same server (they can be in different ASP.NET applications on that server), and use Response.Redirect when you need to redirect to a different server.

Enter Cross-page Postbacks
In ASP.NET 2.0, the cross-page postback feature lets you configure page controls that implement the new IButtonControl interface to post to a different target page from the originating web form. Like Response.Redirect, cross-page postbacks are a client-based transfer mechanism?but like Server.Transfer, the target web page can (usually) access the control values of the source page. To set up a cross-page postback, you specify the target URL in the PostBackUrl property of the source web page.

Implementing Cross-page Postbacks
This section discusses how to implement cross-page postbacks in an ASP.NET 2.0 application. If you’re not already thoroughly familiar with ASP.NET postback operations, you can find out more here.

To begin with, assume that you have two web pages?a source and a target. The source web page initiates the cross-page postback operation using a Button control. You first have to set the PostBackUrl property for the button to the target web page’s URL. Incidentally, all web controls that implement the System.Web.UI.WebControls.IButtonControl interface have the cross-page postback feature enabled by default. The following code snippet shows how to set the property.


When you set the PostBackUrl property, the ASP.NET framework binds the corresponding control to a new JavaScript function named WebForm_DoPostBackWithOptions, generating HTML similar to the following:


With that HTML in place, when a user clicks the button, the browser will submit to the target URL (Target.aspx) rather than to the source URL.

Retrieving Source Control Values from the Target Page
ASP.NET 2.0 provides a new property called PreviousPage that returns a reference to the type of the source page whenever a cross-page post back occurs in your web application. Note that this property contains null (it’s not initialized) when the source and the target web pages are in different applications. Also note that when the target page accesses the PreviousPage property to retrieve the control values of the source page, the ASP.NET runtime loads and executes the source page. That fires the ProcessChildRequest event handler. Moreover, it also fires the Page_Init, Page_Load and any other source page button click events.

So that you can avoid doing all that work accidentally, it’s best to check the IsCrossPostBack Boolean property to determine whether a cross-page postback has actually occurred; the value is true if the target page was requested by a cross-page postback has actually occurred. The value is false if control reached the target web page another way (such as a normal request, a Response.Redirect, or a Server.Transfer). Here’s an example that illustrates how to use this property:

   if ( PreviousPage.IsCrossPagePostBack)     {         //Some code     }   

The PreviousPage property works for both Server.Transfer and cross-page postbacks in ASP.NET 2.0. In ASP.NET 2.0, you can use the PreviousPageProperty after a Server.Transfer operation to retrieve the control values of the source page from within the target page. Here’s an example:

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

The receiving web page can now retrieve the control values of the sender web page as shown in the code snippet below:

   protected void Page_Load(object sender, EventArgs e)   {      if (PreviousPage != null)      {         TextBox txtBox = (TextBox)            PreviousPage.FindControl("txtUserName");             if (textBox != null)            string userName = textBox.Text;         //Other code      }       } 

Notice that the preceding code has to cast the txtUserName control to a TextBox type to access the value. There’s a better way, as you’ll see.

A Better Approach: Using PreviousPageType
The PreviousPageType property provides strongly typed access to a source web page in a cross-page postback operation, letting you retrieve control values from the source page without any typecasting overhead. The code snippets below illustrate how you can use this property.

In the source page you might write:


Note that clicking the button redirects the user to a “Menu.aspx” target page. The target page can retrieve the username and password values using this code:

 <%@ PreviousPageType VirtualPath="~/Login.aspx" %>