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:

/blog/archive/2008/08/22/asp-net-mvc-tip-36-create-a-popup-calendar-helper.aspx

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

image

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

image

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 — ViewsHomeIndex.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.

Download the Code

ASP.NET 5/MVC 6 Training

Learn MVC 6 from Stephen Walther. We fly to you!
Learn More

Discussion

  1. http:// says:

    Why did u make a web service instead of just using a normal MVC route / action? One of the two is lighter/has less of a page life cycle?

  2. http:// says:

    Microsoft should produce a fully supported AJAX/Javascript library as part of its ASP.NET development tools. Our shop cannot incorporate tools like the one cited because it will likely not be supported or developed further after a year or two. We’ve been burned by this before by earlier developers that would introduce whatever custom code library/tool that they wanted. At the end of 7+ years of ASP, ASP.NET, VB6, VB.NET, .NET 1.x and 2.x we have tens of tools/libraries that a) no one knows anything about, b) are from unknown origin, c) are locked into legacy code (vb.net framework 1.x only), d) are buggy and have no forward developement or bug fixes.

    We have source code for some of the problematic tools/libraries but not the budget/manpower to build and fix them (e.g., we have a 50,000 line application that links to a 200,000+ line library of spaghetti like open source vb.net code).

  3. http:// says:

    @Ted — Great feedback! The AJAX Control Toolkit is an open source project. Because it is an open source project, and Microsoft accepts community contributions, Microsoft can’t provide normal support (although, Microsoft does supply community support through the Forums).

    There is a really interesting article on the subjects of the AJAX Control Toolkit, Open Source, and Support at:

    download.microsoft.com/…/AJAX_Control_Case_Study.pdf

    I’m not trying to dismiss your concerns here — just realize that open source opens some difficult issues.

  4. http:// says:

    hi stephen,

    what if i use the server-side controls of AJAX Toolkit with MVC instead of creating everything by hand as you showed here. I know it goes against the MVC principles but what if I use ???

    And I saw that you created a webservice that obtains data from the model layer, but where did you created that web service, I mean, in which layer ? The controllers layer ?

    thanks

  5. http:// says:

    Hi stephen thanks a lot for the valuable article.
    I am a big fan of you.
    At last thanks for the asp.net unleashed book written by u which help me a lat to build very good application in asp.net. I think this is the best book on asp.net

    thanks and regards
    suvrajit ray

  6. http:// says:

    hi stephen,

    im trying to use your example as a base for doing with cascading dropdown list but i cant make it work.
    there are anything in special to make that work with cascading dropdowns?

    thanks!

  7. http:// says:

    Hello Stephen,

    how can I return to the page additional info like ID of the record…

    Thanks

  8. Thank you for that two posts (#36 and #37), they helped me so much !

    However, I’ve just noticed an error in the AjaxExtensions.cs file. By adding the properties in the “Create” call a problem was introduced for calls without parameters (which is the Calendar case).

    AjaxExtensions.cs > Line 80 :
    return Create(helper, String.Empty, clientType, elementId);
    must be replaced by
    return Create(helper, clientType, String.Empty, elementId);

    It solved my problem … I hope it can be useful to someone else

  9. http:// says:

    why are you using web service.without using webservice,we cant create it

  10. vungdv says:

    Hello Stephen,
    My page display this error:

    Message: ‘AjaxControlToolkit’ is undefined
    Line: 68
    Char: 1
    Code: 0
    URI: http://localhost/

    please help me solve this?

  11. Great article, though – thanks!

  12. ASP.NET page represents a class. And, not just any class.

  13. Degrees says:

    This is great. I think the community needs more “real-life” examples of the actual development process. The plumbing of MVC can be studied and applied from books and blogs, but its hard to capture t he process in those.
    online doctorate degree | online high school diploma | accredited degree

  14. Degrees says:

    Let me know what you think of the videos. How can I help you learn MVC? I want your feedback on what topics you want covered in future videos.
    online masters degree | online associate degree

  15. Emilien says:

    I’m trying to follow this but I keep getting :

    Error 1 ‘System.Web.Mvc.AjaxHelper’ does not contain a definition for ‘MicrosoftAjaxLibraryInclude’ and no extension method ‘MicrosoftAjaxLibraryInclude’ accepting a first argument of type ‘System.Web.Mvc.AjaxHelper’ could be found (are you missing a using directive or an assembly reference?)

    Does anyone know what I can do to solve this ?

  16. 243
    I believe it is a promising (currently version 4.0). So I would stick with it.. thanks

  17. HD Video Converter says:

    As the users of HD Camcorders like Sony, Canon, Panasonic, this HD Video Converter is necessary to help us convert hd Video easily and quickly. The Converter for HD provides several practical editing functions to help you achieve ideal output effect. Trim function is to cut videos into clips which you can just convert and transfer to your player. Crop function helps you remove black bars around the movie. You could use Effect function to adjust video brightness, contrast, saturation and more parameters. More powerful and considerate functions are waiting for you to explore.MKV Converter l FLV Converter l DVD Ripper !