views:

191

answers:

2

This code was working properly before, basically I have a master page that has a single text box for searching, I named it searchBox. I have a method to pull the content of searchBox on form submit and set it to a variable userQuery. Here is the method:

Public Function searchString(ByVal oTextBoxName As String) As String
    If Master IsNot Nothing Then
        Dim txtBoxSrc As New TextBox
        txtBoxSrc = CType(Master.FindControl(oTextBoxName), TextBox)
        If txtBoxSrc IsNot Nothing Then
            Return txtBoxSrc.Text
        End If
    End If
    Return Nothing
End Function

The results are displayed on search.aspx. Now, however, if searchBox is filled and submitted on a page other than search.aspx, the contents of the text box are not passed through. The form is very simple, just:

<asp:TextBox ID="searchBox" runat="server"></asp:TextBox>
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="True" PostBackUrl="~/search.aspx" CssClass="searchBtn" />
.

+1  A: 

I think because you are using PostBackUrl, you are going to be required to use the "PreviousPage" identifier to reference your variable.

Another solution would to not use the PostBackUrl property and to capture the event within the user control (I'm assuming you are encapsulating this in one location) and then use the:

Response.Redirect("/search.aspx?sQuery=" & Server.URLEncode(searchBox.Text))

since you are not necessarily passing sensitive data, this should be acceptable as well.

Kyle B.
If you do decide to do the above, the for the love of all that is holy, please make sure you are properly sanitizing that sQuery variable (or using a parameterized query) before you shove it off to your database.
Eoin Campbell
Agreed. Good point. Having a data access layer which properly sanitizes parameters is crucial. That should be the case regardless of whether or not it is being sent through the QueryString.
Kyle B.
I use parameterized queries for all my SQL transactions, however is sanitizing necessary for a search function?
Anders
+1  A: 

I agree with Kyle as to why it doesn't work and the solution if you want to continue to access the value via the text control, but you can also pluck the form data out of the httprequest. I think like this (my asp.net is a bit rusty)

Request.Form[txtBoxSrc.UniqueID]

This plus other techniques (using the previouspage property) are documented here: http://msdn.microsoft.com/en-us/library/6c3yckfw(VS.80).aspx. It seems all you need to do is:

if (Page.PreviousPage != null)
{
    TextBox SourceTextBox = 
        (TextBox)Page.PreviousPage.FindControl("TextBox1");
    if (SourceTextBox != null)
    {
       return SourceTextBox.Text;
    }
}

Updated: Thanks to Jason Kealey for pointing out I needed to use UniqueID.

Tony Lee
I'm guessing the ID will be more complex as it probably is included in user controls, etc.
Jason Kealey
Right! You'll have to get the id from the control
Tony Lee