Sunday, October 11, 2009

Alternative to QueryString Mechanism. ASP.Net Cross posting functionality

Cross Page posting in ASP.NET:
We always tend to post data from one page to another in a typical web application. For example, user name entered on login page getting displayed in welcome message on homepage. How do you generally post values/data from one page to another page in ASP.NET 1.x? There are different ways in which you can exchange the data in ASP.NET 1.x like Query strings, Server.Transfer method, and Response.Redirect method and session variables. All these techniques have their own merits and demerits like browser imposed character limit when passing parameters using Query Strings and indiscriminate usage of session variables can prove costly in terms of load on server and eventually impacts the performance of server.

Keeping in view above limitations in ASP.NET 1.x, Microsoft has reinstated Cross Page posting feature in ASP.NET 2.0. Many of us might not be aware of Cross Page posting feature in classic ASP. Cross Page posting feature allows a page to cross post to another page which in turn allows you to access all data in posted source page.
In ASP.NET 1.x , when you use look at page  life level, you observe that a page can only submit to itself . Cross Page posting feature allows us post the form along with all its control values into another page.

Any server control which implements System.Web.UI.WebControls.IButtonControl   interface can be used for Cross page posting. Examples of such controls include link button, Image button and submit button

By simply setting PostbackUrl property, we specify the destination page to which present page should post when post back occurs on present page.

Different methods to post data:
There are several methods to post data from one page to another page depending on your needs. If you need to exchange simple insensitive data, you can give a try with existing techniques. So, let us revisit those different techniques which allow exchanging data from one page to another.
Response.Redirect method:

We can use this method to allow client browser to do redirection from one page to another page. This technique is usually referred to as Client side redirection. When client browser redirects to DestinationPage.aspx, it involves Server sending a HTTP header informing that the user should redirect and the Client requests the DestinationPage.aspx. Server sends DestinationPage.aspx. Now the Client's address bar shows DestinationPage.aspx.  This entire series of steps incurs extra round trip to server which hits the performance. We usually associate Query Strings with Response.Redirect. There is always a client browser imposed limitation on the length of a query string; so you end up sending small amounts of data over the wire. 
Session Variables:
We can use session variable to store page information and use it across different pages for entire user session. However, this involves of consumption of costly server resources. This approach may prove  disastrous when large numbers of users connect to server and things go pretty poor

     Server.Transfer Method:

     On flip side to Client side redirection, we have server doing the page transfer. In         Server.Transfer, Http Context is preserved when moving from one page to another which means we can access the source page’s items collection in target page. The drawback of using this method is that the browser does not know that a different page was returned to it.  It still displays the previous source page’s URL in the address bar.  This can confuse the user. Transfer is not recommended since the operations typically flow through several different pages.
Technically speaking, Server.Transfer is faster since there is one less roundtrip, but you lose the URL of the page. Server.Transfer also allows for more flexibilty since you can use HTTPContext.Items to pass variables between pages.
Use Server.Transfer when you need to pass context items. Otherwise use Response.Redirect so the user will always see the correct URL in the address bar.

New Properties helping in Cross Page posting:
The new PreviousPage property provides reference to the source page.  When a cross page request occurs, the PreviousPage property of the current Page class holds a reference to the page that caused the post back. 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.  After cross-posts back from source page to the target page, the target page accesses information on the source page using this property.

Different ways of implementing Cross Page Posting:

There are couples of ways of getting control values of the source page into the target page. First way being using FindControl method as discussed below
Using FindControl Method:

In the below listing, we set the PostBackUrl property for Submit button.  This property points to the location of the file to which this page should post.  In this case, it is DestinationPage.aspx.  This means that the DestinationPage.aspx receives the postback and all the values contained in CrossPostingPage.aspx page controls as shown below

 <form id="form1" runat="server">
  <div>
  <h2> This page will cross post to another page by setting PostbackUrl property of submit button.</h2>
      &nbsp;
    <asp:Label ID="lblName" runat="server" Text="LoginName" style="left: 76px; position: relative; top: 20px"></asp:Label><br />
     &nbsp;<asp:TextBox ID="txtPassword" runat="server" style="z-index: 100; left: 160px; position: relative; top: 34px"></asp:TextBox>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit"      
    PostBackUrl="DestinationPage.aspx" style="left: 208px; position: relative; top: 54px" />
    <br />
    <asp:Label ID="lblPassword" runat="server" Text="Password" style="left: 90px; position: relative; top: -12px" Height="4px" Width="43px"></asp:Label></div>
</form>

SourcePage which does Cross page post back to Destination page


You can see in below code how we are able to retrieve values from previous page using FindControl method and display them on Destination Page. Below given output should help you understand the funda.

Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        Label1.Text = "Name:" + CType(PreviousPage.FindControl("txtName"), TextBox).Text
        Label2.Text = "Password:" + CType(PreviousPage.FindControl("txtPassword"), TextBox).Text
   End Sub

Output listing


Using Control Property:


Another way of exposing the control values from the Source Page to Destination Page is to create a public property of controls as shown below
Public Property UserName() As String
        Get
            Return UserName
       End Get
       Set(ByVal value As String)
        End Set
   End Property
    Public Property Password() As String
        Get
            Return Password
        End Get
        Set(ByVal value As String)
        End Set
End Property

Control property
In order to work with the properties described in FindControl page as shown above, PreviousPageType directive should be included in the destination page that is in DestinationPage.aspx. See below listing


<%@ PreviousPageType VirtualPath="FindControl.aspx"%>



The above directive points to FindControl.aspx by specifying the VirtualPath attribute and when that is in place, one can see the properties exposed by FindControl page in DestinationPage using the PreviousPage property. It is always better to expose only the information we need as public properties to reduce the amount of information available to potentially malicious users.



IsCrossPagePostBack Property:


IsCrossPostBack property, which is new in ASP.NET 2.0, enables us to check whether the page is participating in a cross page request.  Using IsCrossPostBack property, we can check whether the request is coming from a particular page or not and act accordingly. As per above example, DestinationPage can include this property to specially process the FindControl.aspx cross page post back. Similarly, we can use the IsValid property of our previous page to make sure the page passed all client validations before it is cross posted to DestinationPage.


If Page.IsCrossPagePostBack Then

            Label1.Text = "Name:" + CType(PreviousPage.FindControl("txtName"), TextBox).Text
            Label2.Text = "Password:" + CType(PreviousPage.FindControl("txtPassword"), TextBox).Text
        Else
           Label1.Text = "No Name:Normal Postback"
            Label2.Text = "No password: normal postback"
        End If
IsCrossPagePostback property


Hence, Cross Page posting is very handy feature to implement very specific scenarios like displaying logged in user details on different pages and ensuring the request is coming from correct page. You can implement this feature in either two ways using FindControl method or exposing values as public properties. PreviousPage object will expose very useful properties like IsValid property and FindControl property to make Cross Page Posting more useful.