ASP.NET 2.0: Cross-page posting from a masterpage

I am currently in the process of writing a website in ASP.NET 2.0. On every page I want to show a search box, that directs the user to a search results page. I have done this by implementing a masterpage with a panel containing a textbox and search button that issues a cross page post (using the PostBackUrl property on the search button). Note that a panel was used so that a default action could be specified, i.e. so when the textbox was in focus and the user hit enter, the cross page post is made).
I could have implemented the search box using a html form (no controls) that posts to the search results page. I could have then interpreted the Request.Form collection. I decided, however, that I wanted to reference controls explicitly. This was done using the following code in the search results page (note the use of PreviousPage.Master.FindControl to get controls on the masterpage).

if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    TextBox search = (TextBox)PreviousPage.Master.FindControl("TextBoxSearchBlog");
    string searchCriteria = Server.HtmlEncode(search.Text);
    Response.Write("Not a cross page postback");

Note that to facilitate SearchResults.aspx correctly responding to posts from any page, I left out the PreviousPageType directive from the search results page, which would normally be in the following format: <%@ PreviousPageType VirtualPath=”~/Default.aspx” %>
Also note that PreviousPage is null if the search is submitted from the SearchResults page with the above code.

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.