Friday 4 November 2011

Cross Page Post backing in .NET


Asp.Net 2.0 fixed this with built-in features that allowed us to easily send information from one page to another.

Button control has property PostBackUrl that can be set to URL of any page in our ASP.Net WebSite where we want to transfer all form values to.


Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows us to get reference to the Page object that initiated the postback (in other words to get the actual reference to the Page object of the aspx page on which user clicked the Submit button on a HTML form).


So for example lets create two sample pages in our Web Application:  
  • SourcePage.aspx
  • DestinationPage.aspx


In SoucePage in Html form we will put two TextBox controls (one for First Name and one for Last Name) and one Button component  and set its PostBackUrl property to "~/DestinationPage.aspx".
SourcePage.aspx:



<form id="form1" runat="server">
<div>
First Name:&nbsp;<asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
Last Name:&nbsp;<asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit To Destination Page"PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />
</div>
</form>
When our user clicks the Submit button, all the values from the HTML Form on SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able to get reference to the SourcePage.aspx in our DestinationPage with the PreviousPage property like this:

So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox controls on SourcePage.aspx and show them in two label controls like this:


    protected void Page_Load(object sender, EventArgs e)
    {
        // first check if we had a cross page postback
        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
        {
            Page previousPage = PreviousPage;
            TextBox firstName = (TextBox)previousPage.FindControl("FirstName");
            TextBox lastName = (TextBox)previousPage.FindControl("LastName");
            // we can now use the values from TextBoxes and display them in two Label controls..
            labelFirstName.Text = firstName.Text;
            labelLastName.Text = lastName.Text;
         }
    }

You probably noticed that we first checked if PreviousPage property of current page (DestinationPage.aspx)is NOT NULL, this is done to avoid running our code in case that user opens our DestinationPage.aspx directly, without running a cross page postback.

Also here we checked the another PreviousPage property called IsCrossPagePostBack to see if we really had a CrossPagePostback.
(If Server.Transfer is used to redirect to this page, IsCrossPagePostBack property will be set to FALSE.

TIP: We can be completely sure that we have a  real CrossPagePostback ONLY IF:
  1. Page.PreviousPage is NOT NULL,
  2. PreviousPage.IsCrossPagePostback is true
This important to check to avoid errors in code.

Now this is very useful and i'm sure you are eager to use this in your next project. But wait, we are not over yet!

Finding the controls on PreviousPage with FindControl method and type-casting them from object to their real type is a little messy.
It feels like there must be a better solution for this!

And here it is: We can use the 
<%@ PreviousPageType %> directive in the header of our DestinationPage.aspx like this
    <%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

to declare our previous page type, and then we can access Public properties of the PreviousPage without typecasting.
Now all we need to do is to create some public properties on our SourcePage.aspx.cs to expose data/Controls we want to the destionation page:


    public partial class SourcePage : System.Web.UI.Page
    {
        public string FormFirstName
        {
            get { return FirstName.Text; }
        }

        public string FormLastName
        {
            get { return LastName.Text; }
        }
    }

And then we can change the Page_Load code in our DestinationPage.aspx to much cleaner code like this:


    protected void Page_Load(object sender, EventArgs e)
    {
        // first check if we had a cross page postback
        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
        {
            SourcePage prevPage = PreviousPage;

            // we can now use the values from textboxes and display them in two Label controls..
            labelFirstName.Text = prevPage.FormFirstName;
            labelLastName.Text = prevPage.FormLastName;     
        }
    }

SourcePage type used in the code is offcourse name of the partial class defined is SourcePage.aspx.cs that inherits System.Web.UI.Page that is automatically created for us when we created new WebForm in VisualStudio.

This code is much cleaner and easier to follow, there is no ugly typecasting, just simple property values to use to retrieve the data from previous page.