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:
<asp:Textbox ID="txtUserName" Runat="server" />
<asp:Textbox ID="txtPassword" Runat="server" />
<asp:Button ID="Submit" Runat="server" Text="Login"
PostBackUrl="Menu.aspx" />
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" %>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
String userName = PreviousPage.txtUserName.Text;
String password = PreviousPage.txtPassword.Text;
//Other code
}
In the preceding code, the
PreviousPageType property returns a strongly typed reference to the source web page, eliminating the need to cast.
ViewState Preserved
For cross-page postbacks, ASP.NET 2.0 embeds a hidden input field named
__POSTBACK that contains the ViewState information of the source web pageprovided the source page contains a server control with a non-null
PostBackUrl property value. The target page can use that
__POSTBACK information to retrieve the ViewState information of the source web page as shown below:
if(PreviousPage!=null && PreviousPage.IsCrossPagePostBack &&
PreviousPage.IsValid)
{
TextBox txtBox = PreviousPage.FindControl("txtUserName");
Response.Write(txtBox.Text);
}
The preceding code checks to ensure that the
PreviousPage property is not
null. Incidentally, the
PreviousPage property contains
null if the target page is not in the same application. The
IsCrossPagePostBack property will be
true only if processing reached the target page due to a cross-page postback operation.
The Cross Page Postback feature, one of the most powerful features in ASP.NET 2.0, allows a web page to postback to another web page and still enable retrieval of the values of the server controls of the source web page from within the target web page seamlessly.