Wednesday, September 15, 2010

Cross page posting in ASP.NET 2.0

Getting Control Values

The Page class exposes a property named PreviousPage. If the source page and target page are in the same ASP.NET application, the PreviousPage property in the target page contains a reference to the source page. (If the page is not the target of a cross-page posting, or if the pages are in different applications, the PreviousPage property is not initialized.) By default, the PreviousPage property is typed as Page. The following code example shows how you can get the value of the TextBox1 control on the source page.

if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
}
The FindControl method finds controls in the current naming container. If the control you are looking for is inside another control (typically, inside a template), you must first get a reference to the container and then search the container to find the control you want to get. In the following code example, the source page contains a Login control with a LayoutTemplate container that in turn contains a TextBox control named UserName. The code gets the value of the UserName control.

Getting Public Property Values from the Source Page

To get public members of the source page, you must first get a strongly typed reference to the source page. You can do so in a number of ways. The first is to include an @ PreviousPageType directive in the target page, which allows you to specify the source page, as in this example:

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

In the target page of a cross-page posting, you can also get the values of public members of the source page. The most common scenario is that the source page defines public properties and you want to get their values on the target page.

public String CurrentCity
{
get
{
   return textCity.Text;
}
}
If the target page contains a PreviousPageType directive that points to the source page, you can access the source page's CurrentCity property using code such as the following
Label1.Text = PreviousPage.CurrentCity;

1 comment: