response.redirect没有在page_load页面上工作

时间:2011-09-13 20:33:06

标签: asp.net postback

我在母版页上有一个文本框,我将其用作搜索框。当用户按下回车时,我想重定向到其他页面,其中包含url参数中的搜索词。

麻烦它似乎只适用于没有自己的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>

在主页page_load中:

    txtSearch.Attributes.Add("onKeyDown", "do_search(this)")

javascript函数,以便当用户按下输入时调用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

它仅适用于没有Page_load的页面,即response.redirect不会在具有page_load的页面上触发。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您可以避免整个进入服务器并重定向。你可以这样做:

function do_search() {
        if (event.keyCode == 13) {
          var textbox = document.getElementById('<%=txtSearch.ClientID%>');
          if(textbox!=null)
             window.location('viewall.aspx?q='+textbox.value);
        }
    }

答案 1 :(得分:1)

好的,谢谢上面的答案,但似乎没有用。我终于通过这篇文章解决了这个问题......这似乎是一个神秘的问题,与浏览器有关。

http://www.pcreview.co.uk/forums/response-redirect-not-working-pressing-enter-key-t2888253.html

第3篇帖子:

“然后我尝试将控件包装成一个 面板并设置Panel的DefaultButton,这似乎得到它 在IE工作。“

我的页面现在如下:

                <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>

......它有效!最后。

答案 2 :(得分:0)

您可以尝试使用RaisePostBackEvent方法,该方法在使用__doPostBack时调用。

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

    if (source == btnSearch)
    {
        Response.Redirect("...");
    }
}
相关问题