Cross Page Posting in ASP.NET 2.0


By default, buttons and other controls in ASP.NET pages post back to the same page that contains the control. Many times during web site development developers need to send user to a different page. We can use Server.Transfer method to move user between pages, however by using this technique the URL doesn't change.

ASP.NET 2.0 introduced new feature that allows you to post back from one page to another, and you can obtain the values of first page controls in the target page. This feature is very useful for multi page form scenario where you want to collect different information on each page. To configure controls to get benefit of the cross page posting the control should have IButtonControl interface implemented. In .NET Framework Button, ImageButton and LinkButton all three implements the IButtonControl interface.

Following is the HTML source code for CrossPagePostingPage1.aspx file. Note the button PostBackUrl property is set to CrossPagePostingPage2.aspx.CrossPagePostingPage1.aspx

<form id="form1" runat="server">
    <asp:TextBox ID="EmailTextBox" runat="server" />
    <asp:Button ID="Button1" runat="server" PostBackUrl="~/CrossPagePostingPage2.aspx" Text="Send " />
</form>

Following code shows you how you can obtain values of previous page controls in CrossPagePostingPage2.aspx

C#

protected void Page_Load(object sender, EventArgs e)
{
    // Check PreviousPage Property of current Page
    // It will be null in case of normal postback
    // It will not be null in case of Cross Page postback

    if (Page.PreviousPage != null)
    {
        // Find Control on Previous Page

        TextBox EmailTextBox = (TextBox)Page.PreviousPage.FindControl("EmailTextBox");

        // Check if Control with the specified name is found

        if (EmailTextBox != null)
        {
            Label1.Text = EmailTextBox.Text;
        }
    }
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Check PreviousPage Property of current Page
' It will be null in case of normal postback
' It will not be null in case of Cross Page postback

    If Page.PreviousPage IsNot Nothing Then

        ' Find Control on Previous Page
        Dim EmailTextBox As TextBox = DirectCast(Page.PreviousPage.FindControl("EmailTextBox"), TextBox)

        ' Check if Control with the specified name is found
        If EmailTextBox IsNot Nothing Then
            Label1.Text = EmailTextBox.Text
        End If

    End If
End Sub​

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments