Tuesday, January 27, 2009

Cross Page postback in ASP.NET

This is a new feature in ASP .NET 2.0. The IButtonControl Interface contains a new property called PostBackUrl which points to the page to which the current page will postback, Button, ImageButton and LinkButton implements this interface and exposes the cross page postback functionality.

When user clicks the button in the current page will postback to the specified page which can access the source page controls through Page.PreviousPage property which returns the reference of previous page, once got the reference of previous page you can use the FindControl method to get the reference of particular or you can expose public properties from source page to provide the type safe access.

For example:
Label1.Text =((TextBox)this.PreviousPage.FindControl("TextBox1")).Text;

In order to provide the strongly typed access to previous page, you can specify the previous page in PreviousPageType directive; since you have strongly typed reference of previous page you can now easily access its public members without any typecasting.

Example:

Create two aspx pages name the first one step_1.aspx and the other step_2.aspx
In the page step_1.aspx put a Text Box named TextBox1
Expose the following properties in code behind file:
public TextBox MyName { get { return TextBox1; } }

In the step_2.aspx put this code in the aspx code:
<%@ PreviousPageType VirtualPath="~/step_1.aspx" %>
Then in the page load event in step_2.aspx page write this code:
Response.Write(this.PreviousPage.MyName.Text);

Source: https://www.nilebits.com/blog/2009/03/cross-page-postback-in-asp-net/

2 comments:

  1. Why do i need to use "PreviousPageType" directive? Is it mandatory to use it?

    ReplyDelete
  2. Dear Tanvir,
    You don't have to use the "PreviousPageType" directive to be able to use cross page postback but in order to provide the strongly typed access to previous page, you can specify the previous page in PreviousPageType directive.

    ReplyDelete