1

I want to do an instant search(on key down make the search) for my website and I don't really know any good way to do it. Until now I did my search on 'enter' key.

I have this code:

<div id="mainsearch" class="search">
       <input class="text-input" value="SEARCH" style="color:#aaa" type="text" id="searchbox" onkeydown="if (event.keyCode == 13){document.getElementById('searchLink').click();return false;}" maxlength="50" runat="server" />
       &nbsp;&nbsp;
       <asp:LinkButton ID="searchLink" runat="server" onclick="searchLink_Click">Search</asp:LinkButton>



       <div id="results" visible="false" class="ac_results" style="position: absolute; width: 298px;" runat="server">
             <asp:Literal ID="litActiveSearch" runat="server"></asp:Literal>
       </div>
</div>

and on my code behind:

    protected void searchLink_Click(object sender, EventArgs e)
    {
        results.Visible = true;
            litActiveSearch.Text = SearchResults(searchbox.Value);
    }

    private string SearchResults(string searchString = "")
    {

        SqlCommand projectCom = new SqlCommand();
      ....
        countCom.CommandText = "SELECT count(ID_PROJECT) FROM PROJECT WHERE TITLE LIKE '%" + searchString + "%' AND DELETE_BIT = 'False' ";


        countCom.CommandType = CommandType.Text;
        //int projectRowCount=0,actorRowCount=0,mediaRowCount = 0;

        int RowCount = 0;
        RowCount = Convert.ToInt32(countCom.ExecuteScalar());

        /*str += "<div class=\"ac_results\" style=\"position: absolute; width: 251px; top: 110.4444465637207px;" +
            "left: 1010.8776870117188px;\">";*/

        str += "<ul>";

        str += " <li class=\"ac_even ac_over\"><a href=\" ../search/search.aspx?q=" + searchString + " \" class=\"startsearch\">St<strong>a</strong>rt <strong>" +
                    "a</strong> full se<strong>a</strong>rch &gt;</a>" +
                "</li>";


        str += " <li class=\"ac_odd\">" +
                    "<span class=\"category\">" +
                        "Projects<a class=\"more\" href=\" ../search/searchProjects.aspx?q=" + searchString + " \" >" + RowCount.ToString() + " results &gt;</a>" +
                    "</span>" +
                "</li>";

    //************ Now show the results ************//
        projectCom.CommandText = "SELECT TOP 3 ID_PROJECT,TITLE,COUNTRY FROM PROJECT WHERE TITLE LIKE '%" + searchString + "%' AND DELETE_BIT = 'False'";
....
}    

on SearchResults() method I run my query which makes a connection with my database in order to get the results on the screen.

It is my first time doing a website, so I don't really know anything.

4

3 回答 3

1

这是一个替代方案

<asp:UpdatePanel runat="server" id="UpdatePanel2" updatemode="Always">
 <ContentTemplate>
    <asp:TextBox ID="searchbox" OnTextChanged="searchbox_TextChanged" 
         runat="server" AutoPostBack="true"/>          
 </ContentTemplate>
</asp:UpdatePanel>

背后的代码

protected void searchbox_TextChanged(object sender, EventArgs e)
{
   litActiveSearch.Text = SearchResults(searchbox.Text);
}

请记住,它litActiveSearch也应该在内部UpdatePanel以更新其值

编辑

如果litActiveSearch在另一个里面UpdatePanel,你需要UpdatePanel像这样配置

<asp:UpdatePanel ID="UpdatePanel3" runat="server">
   <ContentTemplate>
       <asp:Literal ID="litActiveSearch " runat="server"></asp:Literal>
   </ContentTemplate>                                
   <Triggers>
        <asp:AsyncPostBackTrigger ControlID="searchbox" EventName="TextChanged">
        </asp:AsyncPostBackTrigger>
   </Triggers>
</asp:UpdatePanel>
于 2012-09-23T14:40:22.717 回答
0

我使用 AJAX 来解决这个问题。我在不同的 .aspx 文件 (searchHelper.aspx) 中使用了我的 SearchResults() 函数,并使用下面的 ajax 代码来调用它:

 function getSearchResults(e) {

            var searchString = e.value; //document.getElementById("searchbox").value;

            if (searchString == "") {
                document.getElementById("results").innerHTML = "";
                return;
            }
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("results").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "<%=Page.ResolveUrl("~/template/searchHelper.aspx?searchString=")%>"+searchString, true);

            xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"); //solve any AJAX caching problem(not refreshing)
            xmlhttp.send();
 }

我的链接是这样的:

<input class="text-input idle" value="SEARCH" type="text" id="searchbox" onkeyup="javascript:getSearchResults(this);" />
于 2012-11-04T19:06:09.337 回答
0

这是一个完整的工作示例,希望对您有所帮助

aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:TextBox ID="searchbox" OnTextChanged="searchbox_TextChanged" runat="server"
            onkeydown="javascript:setTimeout('__doPostBack(\'searchbox\',\'\')', 0)" />
        <asp:UpdatePanel ID="UpdatePanel3" runat="server">
            <ContentTemplate>
                <asp:Literal ID="litActiveSearch" runat="server"></asp:Literal>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="searchbox" EventName="TextChanged"></asp:AsyncPostBackTrigger>
            </Triggers>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void searchbox_TextChanged(object sender, EventArgs e)
    {
        litActiveSearch.Text = SearchResults(searchbox.Text);        
    }

    private string SearchResults(string searchString)
    {
        if (string.IsNullOrEmpty(searchString))
            return "";

        var datasource = new[]
        {
            new {IdProject = 1, Title = "abcd"},
            new {IdProject = 2, Title = "aabcd"},
            new {IdProject = 3, Title = "bcde"},
            new {IdProject = 4, Title = "defgh"},
            new {IdProject = 4, Title = "defghi"}
        };

        string str = "";

        var query = from p in datasource
                    where p.Title.StartsWith(searchString)
                    select p;

        str += "<ul>";

        str += " <li class=\"ac_even ac_over\"><a href=\" ../search/search.aspx?q=" + searchString + " \" class=\"startsearch\">St<strong>a</strong>rt <strong>" +
                    "a</strong> full se<strong>a</strong>rch &gt;</a>" +
                "</li>";

        str += " <li class=\"ac_odd\">" +
                    "<span class=\"category\">" +
                        "Projects<a class=\"more\" href=\" ../search/searchProjects.aspx?q=" + searchString + " \" >" + query.Count().ToString() + " results &gt;</a>" +
                    "</span>" +
                "</li>";
        return str;
    }
}
于 2012-09-26T09:16:16.727 回答