Andreas Lymbouras
Andreas Lymbouras

Reputation: 1035

Instant search asp.net

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.

Upvotes: 1

Views: 3220

Answers (3)

Andreas Lymbouras
Andreas Lymbouras

Reputation: 1035

I used AJAX to solve this. I used my SearchResults() function in a different .aspx file (searchHelper.aspx) and used the below ajax code to call it:

 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();
 }

and my link is like this:

<input class="text-input idle" value="SEARCH" type="text" id="searchbox" onkeyup="javascript:getSearchResults(this);" />

Upvotes: 0

anouar.bagari
anouar.bagari

Reputation: 2104

This is a alternative

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

Code behind

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

keep in minde that litActiveSearch should also be inside an UpdatePanel to have its value updated

Edit

if litActiveSearch is inside another UpdatePanel you need to configure that UpdatePanel like this

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

Upvotes: 1

anouar.bagari
anouar.bagari

Reputation: 2104

This is a fully working example, hope it will help

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

Upvotes: 0

Related Questions