ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field
In this tip, Stephen Walther demonstrates how you can create an auto-complete text field in an MVC view by taking advantage of the Ajax Control Toolkit. He explains how you can create a custom Ajax Helper that renders the necessary JavaScript.
In the previous tip, I demonstrated how you can take advantage of the client file only version of the Microsoft AJAX Control Toolkit to create a popup calendar that you can use as a date picker. See:
In this tip, I tackle another one of the behaviors in the toolkit. In this tip, I demonstrate how you can use the AutoComplete behavior to add auto-complete functionality to a text field (see Figure 1).
Figure 1 – Using auto-complete with a text field
Add the Client Files to Your MVC Application
The first step is to add the client file only version of the AJAX Control Toolkit to your ASP.NET MVC application. You can download the AJAX Control Toolkit from the following URL:
http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488
This version of the AJAX Control Toolkit does not contain server-side controls or control extenders. It contains only the client-side files – JavaScript, CSS, images – required to use the client-side AJAX behaviors.
After you download the file, unzip it, and add the AjaxControlToolkit folder and all of its contents to the Contents folder in your ASP.NET MVC application. After you copy the folder into your project, your Solution Explorer window should resemble Figure 2.
Figure 2 – Solution Explorer Window with AJAX Control Toolkit Files
Create the AutoComplete Extension Method
The next step is to create an AutoComplete() Helper method that renders includes for all of the necessary JavaScript files and sets up the AutoComplete behavior. The AutoComple() Helper is contained in Listing 1.
Listing 1 – AutoCompleteExtensions.cs
using System.Text; using System.Web.Mvc; namespace AjaxControlToolkitMvc { public static class AutoCompleteExtensions { public static string AutoComplete(this AjaxHelper helper, string elementId, string servicePath, int minimumPrefixLength, int completionSetCount) { var sb = new StringBuilder(); // Add Microsoft Ajax library sb.AppendLine(helper.MicrosoftAjaxLibraryInclude()); // Add toolkit scripts sb.AppendLine(helper.ToolkitInclude ( "AjaxControlToolkit.ExtenderBase.BaseScripts.js", "AjaxControlToolkit.Common.Common.js", "AjaxControlToolkit.Animation.Animations.js", "AjaxControlToolkit.PopupExtender.PopupBehavior.js", "AjaxControlToolkit.Animation.AnimationBehavior.js", "AjaxControlToolkit.Compat.Timer.Timer.js", "AjaxControlToolkit.AutoComplete.AutoCompleteBehavior.js" )); // Create properties var props = new { serviceMethod="GetCompletionList", servicePath=servicePath, minimumPrefixLength=minimumPrefixLength, completionSetCount=completionSetCount }; // Perform $create sb.AppendLine(helper.Create("AjaxControlToolkit.AutoCompleteBehavior", props, elementId)); return sb.ToString(); } } }
The Helper method in Listing 1 adds includes for all of the JavaScript files required to use the AutoComplete behavior. The Helper also calls the Microsoft AJAX Library $create() method to instantiate the AutoComplete behavior and associate it with a DOM element on the page.
Create a Web Service
The AutoComplete behavior calls a web service to get a list of auto-complete items to display. We are going to use the Movie service in Listing 2.
Listing 2 – MovieService.asmx
using System.Linq; using System.Web.Services; using Tip37.Models; namespace Tip37 { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class MovieService : System.Web.Services.WebService { [WebMethod] public string[] GetCompletionList(string prefixText, int count) { var dataContext = new MovieDataContext(); return dataContext.Movies .Where(m=>m.Title.StartsWith(prefixText)) .Take(count) .Select(m => m.Title) .ToArray(); } } }
The Movie service contains a single web method named GetCompletionList() which accepts the following two parameters:
· prefixText – The text the user has entered into the text field so far.
· Count – The number of auto-complete items to return.
Notice that the GetCompletionList() method returns a string array. This array is what gets displayed in the text field associated with the AutoComplete behavior.
Use the AutoComplete Helper Method in a View
Now, we are ready to use the AutoComplete behavior in a view. The view in Listing 3 has a text field with the Id movie. The AutoComplete() helper method is called to associate the AutoComplete behavior with this text field.
Listing 3 -- \Views\Home\Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Tip37.Views.Home.Index" %> <%@ Import Namespace="AjaxControlToolkitMvc" %> <!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>Auto-Complete</title> </head> <body> <div> Movie: <input id="movie" /> <%= Ajax.AutoComplete("movie", "/MovieService.asmx", 1, 10) %> </div> </body> </html>
The Ajax.AutoComplete() Helper method accepts the following parameters:
· The name of the DOM element to which the auto-complete functionality is added
· The URL of a web service
· The number of characters that a user must enter before the auto-complete items start to appear.
· The number of auto-complete items to display.
Summary
Getting the AJAX Control Toolkit AutoComplete behavior to work within an ASP.NET MVC application is not difficult when you have the client file only version of the AJAX Control Toolkit. There are many other useful AJAX behaviors in this toolkit which we will discuss in future tips.