Sunday, September 13, 2009

Cross page postback in ASP.NET

This is the blog post I want to present you something that you need to know. When I was new to IT industry and ASP.NET programming, I believe the ways to access the page1 variables on page2 are as follows.

  • Querystring parameters
  • Session management using session etc..

So, when I want to access the values of page1 on page2, I will store them in a session by creating session variable and will use it in the page2. And another method is, by passing values to page2 in query string parameters from page1. But this need some extra processing on server side to redirect them to that page.

After got little bit experience and when I came to the same situation where I need to pass the parameters from one page to another page, there cross page post back option helped me. So, I want to share the feature with you. This is the third way of passing values from one page to another page.

ASP.NET framework default supports it. There are some parameters to the Page object which helps us to get the logic work.

  • PreviousPage
  • IsCrossPagePostBack

When you want to call server side programming, usually we will write server side control with click event or command event which does the postback and execute server side logic for that event. But when you want to call different page in click event, then you need to use a special property called "PostBackUrl" and to it you need to set the url of the destination page. So, that post back event call that page. This is what the concept called Cross page PostBack.

In programming point of view how to implement this?

ASPX Code: [Page1.aspx]

<asp:TextBox runat="server" ID="tbCrossPageTest"></asp:TextBox>
<asp:Button runat="server" Text="Submit" PostBackUrl="~/Page2.aspx" />

C# Code: [Page2.aspx]

if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            TextBox tb = (TextBox)PreviousPage.FindControl("tbCrossPageTest");
        }

Here, we need to check for some conditions as best practice. One is for whether to know PreviousPage object is null or not and second, is current page from cross page post back. PreviousPage is the object which holds the page1 object and from it, you can find any control on the page and access the values. I know, we don’t use this in many times, but you need to know this option is available in ASP.NET. Please let me know you ideas on it and provide your feedback. Hope this will help you better in understanding the cross page post back.

Note: This cross page post back won't change any of current page properties. For example, page2.IsPostBack is false only, when cross page post back is raised on page1. So, don't confuse.

No comments:

Post a Comment