我现在正在构建一个带有文本框和按钮的搜索页面,可能还会有一个下拉列表,以便稍后过滤结果。我将我的按钮的PostBackUrl设置为我的搜索页面(〜/ search.aspx)。有没有一种简单的方法可以将文本框中的值传递给搜索页面?

有帮助吗?

解决方案

如果您在按钮上设置了PostBackUrl,则第一页上的搜索框字段以及该页面上的任何其他表单字段已经发布到您的搜索页面。诀窍是在search.aspx页面的代码隐藏中访问它们。

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

这是一种方式。还有一些快捷方式,例如在search.aspx页面顶部使用PreviousPageType指令:

<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %> 

有关如何使用它的更多细节,以及第一种方法,可以在这里找到:

http://msdn.microsoft.com/en-us/library/ ms178139.aspx

其他提示

您可以使用useSubmitBehavior =&quot; true&quot;并放一个方法=&quot; get&quot;在表格上。这样它将使用浏览器提交行为,并将文本框的值附加到查询字符串

您还可以使用一些JavaScript来捕获文本框字段中的Enter键按键事件。您可以展开它以执行文本框中文本的验证。 (此示例使用 jQuery

$(document).ready(function(){
    // Event Handlers to allow searching after pressing Enter key
    $("#myTextBoxID").bind("keypress", function(e){
        switch (e.keyCode){
        case (13):
            // Execute code here ...
            break;
        default:
            break;
        }
    });
});

解决了这个问题,前一页是“default.aspx”,但是该控件并不驻留在该页面上。由于我使用母版页,我必须选择大师而不是上一页

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  If PreviousPage IsNot Nothing Then
      Dim txtBoxSrc As New TextBox
      txtBoxSrc = CType(Master.FindControl("searchbox"), TextBox)
      If txtBoxSrc IsNot Nothing Then
          MsgBox(txtBoxSrc.Text)
      End If
  End If
End Sub

<div class="gsSearch">
    <asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
    <asp:Button ID="searchbutton" runat="server" Text="search" 
         UseSubmitBehavior="true" PostBackUrl="~/search.aspx" />
</div>

我不知道为什么你会在那个代码中得到一个空引用,因为我的VB不知道,但是我会尝试做一些你可以尝试的修改。

我知道FindControl返回类型Control ..也许你可以等到将它装入特定类型。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  If PreviousPage IsNot Nothing Then
      Dim txtBoxSrc As New Control
      txtBoxSrc = PreviousPage.FindControl("searchbox")
      If txtBoxSrc IsNot Nothing Then
          MsgBox((CType(txtBoxSrc, TextBox)).Text)
      End If
  End If
End Sub

<div class="gsSearch">
    <asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
    <asp:Button ID="searchbutton" runat="server" Text="search" 
         UseSubmitBehavior="true" PostBackUrl="~/search.aspx" />
</div>

怎么样,这个(对不起):

通过代码隐藏从文本框中获取值,并简单地在控件上设置postbackurl,如下所示:

dim textval = SourceTextBox.text
dim myparam = "George"

searchbutton.PostBackUrl = "~/search.aspx?myparam=" & myparam

你可以把它放在处理按钮点击的功能中,不是吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top