Cross-Page Posting in asp.net using c#

In this tutorial you will learn how to perform cross-page posting in asp.net using c#. In asp.net we normally use web forms that post back themselves only. Under some circumstances, you may need to post one page to another page. For instance, you might be creating a multi-page form that gets different information on each page. In that scenario, you can configure certain controls (those that implement the IButtonControl interface, like Button control) on the page to post to a different target page. This is called as cross-page posting. Cross-page posting is configured for individual controls. you can create a page that posts to different pages depending on which button the user clicks.

In this post we will cover all the aspects. No need to take tension whether pages are using masterpage or not. When you configure a page for cross-page posting, you frequently want to collect information from the source page. This might include the information from controls on the page, the information being posted by the browser, as well as public properties of the source page. Let's have a look over different techniques of cross-page posting. This post is little bit lengthy than my other posts as it is covering all the aspects but guaranteed very helpful post.

Cross-Page Posting in asp.net using c#

1) Server.Transfer()

Server.Transfer() transfers user from one page to another with the complete data of previous page. It is a partial Cross-Page posting technique; I am saying this technique partial because while posting from one page to another the url doesn’t change. The receiving web page has several options to get the data from the first web page. All of these options use the new property PreviousPage() of page class. PreviousPage() represents the originating page in transfer and cross page post back operations. If the source page and target page are in the same ASP.NET application, the PreviousPage() property in the target page contains a reference to the source page. (If the page is not the target of a cross-page posting, or if the pages are in different applications, the PreviousPage() property is not initialized.) By default, the PreviousPage() property is typed as Page. Using the reference in the PreviousPage() property, you can search for controls on the source page and get their value. You typically do this with the built-in FindControl(String) method. Let’s have a look over the sample code used for demo


SourcePage.aspx
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/><br/>
<asp:Button ID="btn_Submit" runat="server" Text="Submit" OnClick="btn_Submit_Click"/>
SourcePage.aspx.cs
protected void btn_Submit_Click(object sender, EventArgs e)
{
Server.Transfer("TargetPage.aspx");
} 
TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox txtName = PreviousPage.FindControl("txtName") as TextBox;
  if (txtName != null)
  {
   // your rest of code will come here
  }
}
Note

If your .aspx page (SourcePage.aspx) is using masterpage then code in Page_Load() event of TargetPage.aspx.cs will be

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
ContentPlaceHolder mpContentPlaceHolder;
TextBox txtName;

/* The id of <asp:ContentPlaceHolder> being used in masterpage like
<asp:ContentPlaceHolder ID="MasterPageContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>*/

mpContentPlaceHolder = (ContentPlaceHolder)PreviousPage.Master.FindControl("MasterPageContentPlaceHolder");

//Now we are searching textbox in mpContentPlaceHolder
if (mpContentPlaceHolder != null)
{
txtName = (TextBox)mpContentPlaceHolder.FindControl("txtName");

  if (txtName != null)
  {
  //Your code will come here
  }

}

}

}
The FindControl(String) method finds controls in the current naming container. If the control you are looking for is inside another control (typically, inside a template), you must first get a reference to the container and then search the container to find the control you want to get.

Server.Transfer() has one major drawback and that is while using the Server.Transfer() approach the url in the browser does not change.

The browser thinks it has been posted back and fetches the content of the first web form, so history and bookmarking suffered.

2) Getting Public Property Values from the Source Page

In the target page of a cross-page posting, you can also get the values of public members of the source page. The most common scenario is that the source page defines public properties and you want to get their values on the target page.

Note
It is strongly recommended that you expose only the information you need as public properties to reduce the amount of information available to potentially malicious users. To get public members of the source page, you must first get a strongly typed reference to the source page.

You can do so via include an @ PreviousPageType directive in the target page, which allows you to specify the source page, as in this example:
<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>
When this directive is included, the PreviousPage() property is strongly typed to the class of the referenced source page. As a consequence, you can directly reference public members of the source page.

SourcePage.aspx
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/><br/>

<asp:Button ID="btn_Submit" runat="server" Text="Submit" PostBackUrl="~/TargetPage.aspx"/>
SourcePage.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class SourcePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

public String FirstName
{
get
{
return txtName.Text;
}
}
}

The above code example shows that source page containing a public property named FirstName that exposes the value of a TextBox control named txtName.

Note
Properties on the source page that are created primarily to expose values for cross-page posting are usually read-only properties. Although the source page can contain public read/write properties, setting a source page property from the target page property generally has no purpose, because the value will not be persisted.


TargetPage.aspx
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="TargetPage.aspx.cs" Inherits="TargetPage" Title="Target Page" %>

<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

<asp:Content ID="Content1" ContentPlaceHolderID="WebDynamicWebContentsPlaceHolder" Runat="Server">
<asp:TextBox ID="txtMyName" runat="server" EnableTheming="false" Text="First Name will come here"></asp:TextBox>
</asp:Content>

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{

if (PreviousPage != null)
{
txtMyName.Text = PreviousPage.FirstName;
}
}

If the target page contains a PreviousPageType directive that refers to the source page, you can get the source page's FirstName property using code given above.

3) PostBackUrl Property

The working of PostBackUrl is the same as Server.Transfer() but using this technique the url changes when we redirect from one web page to another. For transferring data from one web form/web page to another web form/web page this technique is quite handy. It’s quite simple as well. You just have to use the PostBackUrl property of asp:button that will postback the form data to the webpage mentioned in the PostBackUrl property. Let’s have a look over the example

SourcePage.aspx

<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/><br/>

<asp:Button ID="btn_Submit" runat="server" Text="Submit" PostBackUrl="~/TargetPage.aspx"/>

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)

{

if (PreviousPage != null)

{

TextBox txtName = PreviousPage.FindControl("txtName") as TextBox;

if (txtName != null)

{

// your rest of code will come here

}

}

}
Note: - If your .aspx page (SourcePage.aspx) is using masterpage then code in Page_Load() event of TargetPage.aspx.cs will be

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)

{

if (PreviousPage != null)

{

ContentPlaceHolder mpContentPlaceHolder;
TextBox txtName;

//The id of <asp:ContentPlaceHolder> being used in masterpage like
/* <asp:ContentPlaceHolder ID="MasterPageContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>*/

mpContentPlaceHolder = (ContentPlaceHolder)PreviousPage.Master.FindControl("MasterPageContentPlaceHolder");

//Now we are searching textbox in mpContentPlaceHolder
if (mpContentPlaceHolder != null)
{
txtName = (TextBox)mpContentPlaceHolder.FindControl("txtName");
if (txtName != null)
{
}
}

}

}
Note

If you are using the PostBackUrl property of the asp button then don’t fire the onClick event of that asp button.

But this approach is still not very much effective if we want to assign the PostBackUrl property of the asp button after some certain if/else checks. We can set the page name in PostBackUrl by using c# code on page load event of page but what should we do if we want to set the page name in PostBackUrl using client side javascript after getting some user interaction and then have to decide which page user should redirect. To handle this scenario and to receive form data with more simple way the next technique is very handy and effective. You can call this 3) custom cross-page posting technique.

Custom cross-page posting technique

SourcePage.aspx
<script language="javascript">
<!--
function NoPostBack(sFormAction)
{

var _Post="Default.aspx";
var checkPoint = document.getElementById("<%=txtName.ClientID %>").value;
alert(checkPoint);
if (checkPoint == "Adeel")
{
_Post = "TargetPage.aspx";
document.forms[0].action = _Post;
document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
}
else if (checkPoint == "Maaz")
{
_Post = "anotherpage.aspx";
document.forms[0].action = _Post;
document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
//document.forms[0].target = "_blank";
}
else
{
return false;
}


}-->
</script>

<p>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</p>

<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" EnableTheming="false" OnClientClick="NoPostBack(this.id);"/>

</p>
Using javascript custom function we are performing cross-page posting. document.forms[0].target = "_blank" means the next page will be open in new window. If you don’t want to open next page in new window then comment this line of code. In this above example, sourcepage.aspx is relying on masterpage. Now let’s have a look over the Target page that will get the value of this form.

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{

if (Request.Form != null && Request.Form.Count >0)
{
Label1.Text = Request.Form["ctl00$ContentPlaceHolder1$txtName"].ToString();
}
}

Hay, you are surprised to see this ctl00$MyWebsiteWebContentsPlaceHolder$txtName instead of txtName, now let me explain. In this example The sourcepage.aspx is using masterpage and when I post the form data then after rendering, the id of textbox changes from txtName to ctl00$MyWebsiteWebContentsPlaceHolder$txtName . The new id ctl00$MyWebsiteWebContentsPlaceHolder$txtName contains the reference of masterpage. See the image below.


cross-page posting using masterpage

But if your page is not relying on masterpage then you will get same id of textbox which is txtName in Target.aspx page like mentioned in below image.


cross-page posting without using masterpage

So these are the ways to perform cross-page posting in asp.net using c#. I hope you will find this article very handy.

0 comments: