Strongly-typed access to previous page during cross-page postback

ASP.NET 2.0 introduced the concept of cross-page postbacks where one page could postback information to a page other than itself. This is done by setting the PostBackUrl property of a button to the name of the page that the button should postback data to. Normally, the posted data can be accessed by doing something like

PreviousPage.FindControl("ControlID").

However, this requires a cast if you need to access properties of the target control in the previous page (which you normally need to do). If you add a public property into the code-behind page that initiates the postback operation, you can access the property in a strongly-typed manner by adding the PreviousPageType directive into the target page of the postback.
For example, if you have a page called Default.aspx that exposes a public property that returns a Textbox that is defined in the page, the page that data is posted to (lets call it SearchResults.aspx) can access that property in a strongly-typed manner and intellisense support  by adding the PreviousPageType directive into the top of the page:

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

By adding this directive, the code in SearchResults.aspx can access the TextBox defined in Default.aspx in a strongly-typed manner. The following example assumes the property defined in Default.aspx is named SearchTextBox.

TextBox tb = PreviousPage.SearchTextBox;

This code obviously only works if the previous page is Default.aspx other wise runtime exception is thrown.  PreviousPageType also has a TypeName property as well where you could define a base type that one or more pages derive from to make this technique work with multiple pages.

, , , , ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Share to Facebook Share to Twitter Stumble It Share on Tumblr Digg More...