即时搜索asp.net

时间:2012-09-23 14:15:59

标签: c# javascript asp.net ajax

我想为我的网站做一次即时搜索(关键下来进行搜索),我真的不知道有什么好办法。到现在为止,我在“输入”键上进行了搜索。

我有这段代码:

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

以及我的代码背后:

    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()方法我运行我的查询,该查询与我的数据库建立连接,以便在屏幕上显示结果。

这是我第一次做网站,所以我什么都不知道。

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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;
    }
}

答案 2 :(得分: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);" />