Cross Page Posting In ASP.NET 2.0

Posted by: Suprotim Agarwal , on 8/5/2007, in Category ASP.NET
Views: 92623
Abstract: Cross-page posting is desired in a scenario where data is collected on one Web page and processed on another Web page. ASP.NET 2.0 introduces a new property in the Page class called ‘PreviousPage’ which gets the page that posted to the current page . In this article, we will see how to use Cross Page Posting in ASP.NET 2.0. I assume that you have some experience in creating ASP.NET pages.
Cross Page Posting In ASP.NET
 
ASP.NET by default, submits the form to the same page. Cross page posting is submitting the form to a different page. This is usually required when you are creating a multi page form to collect information from the user on each page. When moving from the source to the target page, the values of controls in the source page can be accessed in the target page.
To use cross-page posting, you have to use the PostBackURL attribute to specify the page you want to post to.
 
Follow these steps :
 
Step 1: Create a new ASP.NET website called CrossPagePosting. By default, the website is created with a single webpage, Default.aspx. Right click the project in the Solution Explorer > Add New Item >Web Form. Keep the original name Default2.aspx and click ‘Add’. The website will now contain two pages, Default.aspx and Default2.aspx.
 
Step 2: On the source page, Default.aspx, drop a button on the form. Set the text of the button as ‘TargetButton’. Set the ‘PostBackUrl’ property of a Button to the URL of the target page, Default2.aspx.
 
<asp:Button ID="Button1" runat="server" PostBackUrl="~/Default2.aspx" Text="TargetButton" /></div>
 
Step 3: In the target page Default2.aspx, drop a label on the page from the toolbox.
 
Step 4: In the Page_Load() of Default2.aspx, you can then access the ‘PreviousPage’ property to check if the page is being accessed as Cross Page postback.
 
protected void Page_Load(object sender, EventArgs e)
{
       if (Page.PreviousPage != null)
       {
 }
}
 
 
Step 5: To retrieve values from the source page, you must access controls using the ‘FindControl()’ method of the ‘PreviousPage’. We will be accessing the Text property of the Button control placed in Default.aspx.
 
 
protected void Page_Load(object sender, EventArgs e)
{
        if (Page.PreviousPage != null)
        {
            Button btn = (Button)(Page.PreviousPage.FindControl("button1"));
            Label1.Text = btn.Text;
        }
 
}
 
 
Step 6: In the Solution Explorer, right click Default.aspx > ‘Set as Start Page’. Run the application and click on the button. As you can observe, the page is posted to Default2.aspx and the value containing the name of the button control gets displayed in the label.
 
Difference between Server.Transfer and Cross Page Posting
 
One could argue that even the ‘Server.Transfer’ method can be used to move between pages. However there are a few differences between ‘Server.Transfer’ and ‘Cross Page’ Posting.
In ‘Server.Transfer’, the URL doesn't change whereas in cross page posting, the form is submitted to a different page, thereby changing the url.
The Server.Transfer method is a server-based operation whereas cross-page postback is a client-based transfer.
Note: To determine whether the page was invoked from a cross-page posting or a Server.Transfer operation, the Page class exposes a property named IsCrossPagePostBack.
 
Tips and Tricks
 
Tip 1: If you are using a MasterPage for all your pages, you can access the control using the following code.
Assuming that the content id and placeholder id is named ‘Content1’.
ContentPlaceHolder pageContent =
(ContentPlaceHolder)
(Page.PreviousPage.Form.FindControl ("Content1"));
TextBox1.Text = pageContent.FindControl("button1");
 
Tip 2: To avoid casting the control type, you can also access the previous page data(Default1.aspx) by creating public properties that expose the data that you need to access.
 
In Default1.aspx
 
public String BTarget
{
        get
        {
             return button1.Text;
        }
}
 
In the ‘Default2.aspx’, access the value of the Button using the exposed property
 
Label1.Text = PreviousPage.BTarget;
 
 
Conclusion
 
In this article, we saw that ASP.NET 2.0 introduces new features whereby pages can post to pages other than themselves. We also examined the differences between Server.Transfer and Cross Page Posting. I hope this article was useful and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim received the prestigious Microsoft MVP award for 17 consecutive years, until he resigned from the program in 2025. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Raja on Wednesday, August 8, 2007 3:27 AM
Hi

I am exposing the property to get the value from previouspage. But i am getting the error "System.web.Ui.page does not contain a definition for ITarget"; Why i am getting thiserror. Pl give me the solutions.

Default1.aspx

string str = Page.PreviousPage.ITarget;
Response.Write(str);

Default.aspx

public string ITarget
    {
        get { return TextBox1.Text; }
      
    }
Comment posted by Raja on Wednesday, August 8, 2007 3:34 AM
Hi

I am exposing the property to get the value from previouspage. But i am getting the error "System.web.Ui.page does not contain a definition for ITarget"; Why i am getting thiserror. Pl give me the solutions.

Default1.aspx

string str = Page.PreviousPage.ITarget;
Response.Write(str);

Default.aspx

public string ITarget
    {
        get { return TextBox1.Text; }
      
    }
Comment posted by Suprotim Agarwal on Saturday, August 25, 2007 9:06 AM
Hi Raja,
In the code behind of the target page, try defining a variable of the type of the first page and set its value to Page.PreviousPage.

HTH,
Suprotim Agarwal

Thanks.
Comment posted by Jhansi on Monday, September 10, 2007 10:14 AM
Hi
i am writing a code for to view the previous records & next records.i taken a session.
//Next btn

            counter = (int)Session["n"];
            txtname.Text = ds.Tables[0].Rows[counter]["Name"].ToString();
            txtid.Text = ds.Tables[0].Rows[counter]["id"].ToString();
            Session["n"] = counter + 1;


//for previous btn
counter = (int)Session["n"];
            txtname.Text = ds.Tables[0].Rows[counter]["Name"].ToString();
            txtid.Text = ds.Tables[0].Rows[counter]["id"].ToString();
            Session["n"] = counter - 1;

..................//
But i m geting only next records.I m not get'g previous records when i was at last record.I dont know where i did wrong.Plz sir ......Try to co-operate with me.
Thank you



Comment posted by Suprotim on Thursday, September 20, 2007 7:27 AM
Sorry for the delay in answering. Are you still facing a problem? Let me know and I will try and find a solution to it.
Comment posted by Neeraj Kumar on Tuesday, October 23, 2007 7:20 AM
I think to excess the exposed property previous page instance is required. there is no method to access these directly like PreviousPage.BTarget; without setting the instance.?
Comment posted by Nagarajan on Monday, November 12, 2007 12:31 AM
i need one page value how to get the second page?
for exe:
one page value=textbox1.text="string"
this string how to diplay second page?
Comment posted by Suprotim Agarwal on Monday, November 12, 2007 8:12 AM
Hi Nagarajan,
You could use properties as demoed in the Tips and Tricks section
OR use this code :
if (Page.PreviousPage != null)
{
    TextBox txt = (TextBox)(Page.PreviousPage.FindControl("textbox1"));
  // Assuming TextBox2 is on second page
  TextBox2.Text = txt.Text;
}
Comment posted by dada2000 on Friday, November 30, 2007 5:16 AM
Hello,
I'm getting a stranger error.
I use sNomAgence = PreviousPage.DDarwinSelectedValue.ToString(); to access the public property DDarwinSelectedValue of the previous page, I specified <%@ PreviousPageType VirtualPath="ListePointsNonMatches.aspx" %>
everything go well, but when I try to publish (not when I compile and run locally the web), it throw an error "ListeSI.aspx does not contain a definition for DDarwinSelectedValue", where ListeSI is another page which have nothing to do with it... To fix it, I used your "findControl" method, and now it's working. I think it's linked to the fact that I use a master page, but I don't understand why this error is only throw when I publish the web site. I'm the only one getting this error (or bug?) ?
Comment posted by Suprotim Agarwal on Monday, December 3, 2007 10:26 PM
Hi dada, Do you have any page called ListeSi.aspx in your project which in turn is linked or redirected to ListePointsNonMatches.aspx?
Comment posted by Nikhilesh Sorte,Harshal Nimje,Amol Gathle on Wednesday, December 26, 2007 11:49 AM
It Is one Of the Best Document
Comment posted by DreamBig on Thursday, February 28, 2008 12:47 AM
My Problem is:
On the first page, I have few dropdownlist,radiobuttonlist & a textbox.
Now from one dropdownlist,on the basis of a given value selected from the dropdownlist,On the second page,in the gridview a new column needs to be added.
how this can be done?
Comment posted by c on Sunday, June 15, 2008 9:15 AM
cnv adsfas as sfafsa a
Comment posted by test on Friday, February 13, 2009 9:25 PM
adfadjfalkdjfdkajfkdjfkadjfa
Comment posted by divya on Wednesday, October 28, 2009 6:44 AM
i am using cross page post back. but previous page becomes null when i hit on the address bar of the target page.. how to solve this..

its very urgent..please help me
Comment posted by Nagajyothi on Thursday, October 29, 2009 8:33 AM
This code very use full.Thanks
Comment posted by pragnesh dineshbhai on Sunday, December 6, 2009 9:36 AM
code is very usefull.
best thing give in step.thnks.......................
Comment posted by Csaba Áll on Monday, February 1, 2010 2:09 PM
Cross Page Posting is good with simple controls placed on a web Page.
My problem concerns using HyperLinkField in a GridView row, which is using Dynamic Query String (data is taken from the current gridview row). In this case, how can I get CrossPagePosting? In fact, the HyperLinkField cannot use data from outside the GridView (i.e. a DropDownList contains 'Years' in the top of the page that is intended to be used for filtering the period in the second web page). Alternatively, I could use public properties on the initial web page but these are not accessible on the second web page, because we are not in a 'CrossPagePosting' scenario.
On the second web page (invoked by the normal Post operation), I need to gather data from the QueryString as well as from the PreviousPage's controls, or public properties. I guess there is an incompatibility between these requirements.
Do have somebody an idea, or some workaround?
Thanks in advance.
Comment posted by Kali Raj on Tuesday, May 4, 2010 5:28 AM
Good Example
Comment posted by Kali Raj on Tuesday, May 4, 2010 5:29 AM
Good Example
Comment posted by Ayman Mostafa on Saturday, July 17, 2010 3:48 PM
Hi thank you for the great demonstration; however iam getting a wired issue.

when i tried the tip2, the public property in the default.aspx can't be used in the default2.aspx

Could you please help me! and thank you so much for your valiable post.


Default1.aspx=ayman.aspx
~~~~~~~~~~~~~~~~~~~~~~~~~

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    public void Page_Load(object sender, EventArgs e)
    {
        
      
    
    }

    public string BT

    {

        get

        {

            return TextBox1.Text;
        }
    }

    
    
    
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
            
        <asp:TextBox ID="TextBox1" runat="server"/>
    
        <br />
        <asp:Button  ID="Button1" runat="server" Text="Submit button"   PostBackUrl="~/ayman2.aspx" />
    
    </div>
    </form>
</body>
</html>


Default2.aspx=ayman2.aspx
~~~~~~~~~~~~~~~~~~~~~~~~~

<%@ Page Language="C#"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    public void Page_Load(object sender, EventArgs e)
    {





        Label1.Text = PreviousPage.BT;
        
        
    }
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server" Text="Label" />
    
    </div>
    </form>
</body>
</html>


Error when trying to start without debugging:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Compiler Error Message: CS1061: 'System.Web.UI.Page' does not contain a definition for 'BT' and no extension method 'BT' accepting a first argument of type 'System.Web.UI.Page' could be found (are you missing a using directive or an assembly reference?)



Line 14:         Label1.Text = PreviousPage.BT;
Comment posted by Brian on Tuesday, April 5, 2011 1:22 AM
My query is that i am generating input button dyanimically like
<input id='4245' type='image' size='10px' value='View' src='http://61.12.31.77:81/Images/ECommerce/View button.png'   /> through string builder from page side and i want to do postback to next [page on click of the button but with that i want to use id of the button on next page in session variable.. So i want to know how do i pass url on click and on next page how can i retrieve id of button on next page..
$(this).siblings('.current').removeClass('current'); $(this).addClass('current'); $('.tabContent').children('.current').removeClass('current'); $('.tabContent').children().eq($(this).index()).addClass('current'); }); });