Subscribe to this Blog

Subscribe to this Blog

ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field - Stephen Walther on ASP.NET MVC

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:

http://weblogs.asp.net/stephenwalther/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

clip_image002

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

clip_image004

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.

Download the Code

Published Saturday, August 23, 2008 7:04 PM by swalther
Filed under: , , ,

Comments

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Saturday, August 23, 2008 11:02 PM by PK

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?

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Monday, August 25, 2008 7:49 PM by brucesinner

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

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Tuesday, August 26, 2008 2:15 AM by Suvrajit Ray

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

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Friday, September 5, 2008 6:16 PM by brucesinner

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!

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Friday, November 7, 2008 4:43 AM by carrot

Hello Stephen,

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

Thanks

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Tuesday, November 11, 2008 10:33 AM by Pierre MARTIN

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

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Tuesday, November 18, 2008 5:05 AM by abc

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

# re: ASP.NET MVC Tip #37 – Create an Auto-Complete Text Field

Saturday, November 29, 2008 8:03 AM by slawek.rosiek

how to do it without webservice - with using actions? I change service path to "/controller" and service method to "action" which return Json but when I write something to textbox the action isn't invoked