Over the weekend I built this "SuggestTextBox" control. It uses Ajax.NET to dynamically load items to "suggest" to the user when they are entering data into a textbox. It uses some of the same logic of the AutoSuggestBox off of CodeProject, though I altered it to use the Ajax.NET instead of straight ajax. I believe this offers a cleaner and more intuitive model. As of right now the javascript needs to be cleaned up quite a bit, though it's working.
It's fairly simple to use:
<cc1:SuggestTextBox ID="suggester" runat="server" MenuCssClass="SuggestMenu" ItemCssClass="SuggestMenuItem" SelectedItemCssClass="HighlightStyle" SuggestedItemsClassDefinition="Utils.GetHtmlItems" KeyPressDelay="100" CssClass="TextBox"></cc1:SuggestTextBox>
The noted properties are the SuggestedItemsClassDefinition, which is the class/method that get's attributed with [AjaxMethod], and they KeyPressDelay which is the delay in milliseconds on how fast to fetch the data after the user types.
Here's the class that actually returns the data from the data source. Just using bogus data in this example. The SuggestItem class contains a method named GetHtml which renders the needed html for the menu item.
public class Utils
{
/// <summary>
/// Gets the HTML.
/// </summary>
/// <param name="key">The key we would look for.</param>
/// <param name="textBoxID">The text box ID.</param>
/// <param name="divID">The div ID.</param>
/// <param name="itemCssClass">The item CSS class.</param>
/// <returns></returns>
[AjaxPro.AjaxMethod]
public string GetHtmlItems(string key, string textBoxID, string divID, string itemCssClass)
{
if (String.IsNullOrEmpty(key))
return String.Empty;
int length = key.Length;
Collection<SuggestItem> items = new Collection<SuggestItem>();
for (int i = 0; i < length; i++)
{
SuggestItem item = new SuggestItem();
item.Label = String.Format("Item {0}", i);
item.Value = i.ToString();
item.CssClass = itemCssClass;
item.IsSelectable = true;
items.Add(item);
}
string html = String.Empty;
for (int j = 0; j < items.Count; j++)
{
html += items[j].GetHtml(j, textBoxID, divID);
}
return html;
}
}
When using Ajax.NET there is a little bit of setup. On the page that is using the Ajax.NET class you need to register the type like this:
AjaxPro.Utility.RegisterTypeForAjax(typeof(Utils));
You also need to register the Ajax.NET handler in your web.config file.
<xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="ajaxNet">
<section name="ajaxSettings" type="AjaxPro.AjaxSettingsSectionHandler, AjaxPro.2"/>
<sectionGroup>
<configSections>
<ajaxNet>
<ajaxSettings>
<urlNamespaceMappings>
<urlNamespaceMappings>
<jsonConverters>
<jsonConverters>
<ajaxSettings>
<ajaxNet>
<appSettings/>
<connectionStrings/>
<system.web>
<httpHandlers>
<add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>
<httpHandlers>
<system.web>
<configuration>
You can download the source and a demo website on my software page.