I am working on a rich content app for one of my talks at TechEd Europe and I thought it would be a good idea to implement a search box with an autocomplete of the past search quires. The intuition here is that the changes are someone else has searched for the same thing you are searching for, so past queries is an interesting set of options to offer. Not to mention it is fun to look at what other people are searching for
What I think is cool about this is I was able to implement it with less than 10 lines of code and absolutely no database specific logic. I did this with a combination of the ASP.NET 2.0 profile store and the ASP.NET AJAX AutoCompleteExtender…
Here is an example screenshot and all the code\markup required… I’d love to hear what you think… do you think this makes for a compelling demo?
Html for search box and “submit” link (default.aspx)
<div id="links"> Search for <asp :TextBox ID="searchtext" runat="server" CssClass="searchbox" ></asp> <asp :LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">go</asp><br /> </div>
ASP.NET handler for the LinkButton (default.aspx)
protected void LinkButton1_Click(object sender, EventArgs e)
{
StringCollection list = Profile.SearchTerms;
if (!list.Contains(searchtext.Text))
{
list.Add(searchtext.Text);
}
//TODO: Do search
}
ASP.NET AJAX goodness (default.aspx)
<asp :ScriptManager ID="ScriptManager" runat="server" />
<asp :AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="searchtext"
runat="server" ServiceMethod="GetCompletionList"
ServicePath="~/SearchAutoComplete.asmx" MinimumPrefixLength="1" />
Web Service Implementation (SearchAutoComplete.asmx)
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
StringCollection list = (StringCollection)HttpContext.Current.Profile["SearchTerms"];
List<string> suggestions = new List</string><string>();
foreach (string s in list)
{
if (s.StartsWith(prefixText))
{
suggestions.Add(s);
}
}
return suggestions.ToArray();
}
</string>
Profile Config Section – (Web.config in
<profile>
<properties>
<add name="SearchTerms"
type="System.Collections.Specialized.StringCollection"
serializeAs="Xml" />
</properties>
</profile>
Exercises left for the user
* Clean up any bad or misleading search terms
* Sort hits by relevance
* Add a hit count
* Age out older results
Demo: http://www.google.com
Source: http://blogs.msdn.com/brada/archive/2006/10/27/search-autocomplete-with-asp-net-ajax-extensions.aspx

Related Listings:

RSS feed for comments on this post. TrackBack URL
July 2nd, 2009 at 4:26 pm
[...] Read the rest here: Search Autocomplete with .NET [...]
July 3rd, 2009 at 6:01 pm
It would have been better if you showed alternate technology (perhaps jQuery) as opposed to using the ASP.NET AJAX AutoCompleteExtender.