【问题标题】:response.redirect not working on page with page_loadresponse.redirect 在 page_load 页面上不起作用
【发布时间】:2011-09-13 20:33:06
【问题描述】:

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

麻烦的是,它似乎只适用于没有自己的 page_load 订阅的页面。

            <div id="search-bar">
                <asp:TextBox ID="txtSearch" runat="server" Text=""></asp:TextBox>
                <asp:Button ID="btnSearch" runat="server" style="display:none"/>
            </div>

在母版页页面加载:

    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 的页面上触发。

有什么想法吗?

【问题讨论】:

    标签: asp.net postback


    【解决方案1】:

    你可以避免整个去服务器和重定向。你可以这样做:

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

    【讨论】:

    • 是的,我试过了,它仍然停留在同一页面上......难以置信。
    • 如果您尝试了该操作并停留在同一页面上,则您可能遇到了 javascript 错误,或者您没有正确捕获回车键。我敢打赌是后者。我的观点是,您不需要通过发回服务器来重定向用户;您可以使用 window.location....从客户端完美地做到这一点....
    【解决方案2】:

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

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

    第三次发帖:

    “然后我尝试将控件包装在 面板并设置面板的默认按钮,这似乎得到了它 在 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>
    

    ...它的工作原理!最后。

    【讨论】:

    • 设置 DefaultButton 属性只是将 javascript 添加到页面以执行 form.submit。我很高兴它有效,但 window.location 方法也必须有效,否则我将戒酒。
    【解决方案3】:

    您可以尝试使用 RaisePostBackEvent 方法,每当使用 __doPostBack 时都会调用该方法。

    protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
    {
        //call the RaisePostBack event 
        base.RaisePostBackEvent(source, eventArgument);
    
        if (source == btnSearch)
        {
            Response.Redirect("...");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 2014-10-17
      • 2013-01-27
      • 2011-10-14
      • 1970-01-01
      相关资源
      最近更新 更多