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
SourcePage.aspx:
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:
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:
- Page.PreviousPage is NOT NULL,
- PreviousPage.IsCrossPagePostback is true
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
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:
And then we can change the Page_Load code in our DestinationPage.aspx to much cleaner code like this:
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.