Reputation: 7153
I have a textbox onin a masterpage which I'm using as a search box. When the user presses enter I want to redirect to an other page with the search terms in the url paramaters.
Trouble it only seems to work on pages that don't have their own page_load subs.
<div id="search-bar">
<asp:TextBox ID="txtSearch" runat="server" Text=""></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" style="display:none"/>
</div>
IN masterpage page_load:
txtSearch.Attributes.Add("onKeyDown", "do_search(this)")
javascript function so that when user presses enter it calls btnSearch_Click
function do_search() {
if (event.keyCode == 13) {
var invisibleButton = document.getElementById('<%=btnSearch.ClientID %>');
__doPostBack(invisibleButton.name, '');
}
}
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
If Trim(txtSearch.Text) <> "" Then
Response.Redirect("viewall.aspx?q=" & txtSearch.Text, True)
End If
End Sub
It only works on pages that don't have a Page_load i.e. the response.redirect doesn't fire on pages with a page_load.
Any ideas?
Upvotes: 0
Views: 3213
Reputation: 7153
Ok, thanks for the answers above but didn't seem to work. I finally got around this via this article...it seems a mysterious problem and is browser related.
http://www.pcreview.co.uk/forums/response-redirect-not-working-pressing-enter-key-t2888253.html
3rd post down:
"I then tried wrapping the controls in a Panel and set the Panel's DefaultButton and that seemed to get it working in IE."
My page now is as follows:
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
<asp:TextBox ID="txtSearch" runat="server" Text=""></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Style="display: none" />
</asp:Panel>
...and it works! finally.
Upvotes: 1
Reputation: 46047
You can try using the RaisePostBackEvent method, which is called whenever __doPostBack
is used.
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
//call the RaisePostBack event
base.RaisePostBackEvent(source, eventArgument);
if (source == btnSearch)
{
Response.Redirect("...");
}
}
Upvotes: 0
Reputation: 63956
You can avoid the whole going to the server and redirecting. You can simply do this:
function do_search() {
if (event.keyCode == 13) {
var textbox = document.getElementById('<%=txtSearch.ClientID%>');
if(textbox!=null)
window.location('viewall.aspx?q='+textbox.value);
}
}
Upvotes: 1