jquery-ui-logo

jQuery UI autocomplete with ASP.NET Web API

jQuery UI autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Step 1 : Getting Web Api Ready

Lets first create a web api method that will return a list of item (Artists) using the search term query sent from the autocomplete textbox. In this post I am not using database, instead I’ll be using List to keep this example as simple as possible.

Below is how I have defined my Artist class

public class Artist
{
    public int Id { get; set; }
    public int Name { get; set; }
}    

Next I have created a Web Api GET method that will use the search term entered in the autocomplete textbox and with a little help of LINQ will return a list of matching results.

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Autocomplete.Controllers
{
    public class ArtistApiController : ApiController
    {

        public List<Artist> ArtistList = new List<Artist>
        {
            new Artist{Id = 1, Name = "Sonu Nigam"},
            new Artist{Id = 2, Name = "Sunidhi Chauhan"},
            new Artist{Id = 3, Name = "Shreya Goshal"},
            new Artist{Id = 4, Name = "Mohit Chauhan"},
            new Artist{Id = 5, Name = "Nihkil Dsouza"},
            new Artist{Id = 6, Name = "Kailash Kher"},
            new Artist{Id = 7, Name = "Atif Aslam"},
            new Artist{Id = 8, Name = "Ali Zafar"},
            new Artist{Id = 9, Name = "Shafaqat Ali"},
            new Artist{Id = 10, Name = "Shankar Madahevan"}
        }; 


        // GET api/values
        public IEnumerable<Artist> Get(string query)
        {
            return ArtistList.Where(m => m.Name.Contains(query)).ToList();
        }
    }
}   

Our server side code is ready ! Time to test it out.

autocomplete test

Step 2 : Client side code

Include jquery-ui.js and jquery.ui.css in your html

<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.8.20.min.js" ></script>
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />

<div id="body">
    <label for="autocomplete-textbox">Search : </label>
    <input type="text" id="autocomplete-textbox" />
</div>

<script type="text/javascript">
$(document).ready(function (){
$('#autocomplete-textbox').autocomplete({
    source: function (request, response) {
        // prepare url : for example '/api/artistapi?query=sonu
        var autocompleteUrl = '/api/artistapi' + '?query=' + request.term;
        $.ajax({
            url: autocompleteUrl,
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (json) {
                // call autocomplete callback method with results  
                response($.map(json, function (data, id) {
                    return {
                        label: data.Name,
                        value: data.Id
                    };
                }));
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                console.log('some error occured', textStatus, errorThrown);
            }
        });
    },
    minLength: 2,
    select: function (event, ui) {
        alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
        $('#autocomplete-textbox').val(ui.item.label);
        return false;
    }
});
});
</script>

One thing to note here is that inside the success method I have used the following code :

response($.map(json, function (data, id) {
    return {
        label: data.Name,
        value: data.Id
    };
}));

data.Id and data.Name is used because in the ajax response (as shown below) data is returned in this format.

autocomplete ajax response

Step 3 : Test & Output :

autocomplete output

Hope this helps :)

2 comments on “jQuery UI autocomplete with ASP.NET Web API

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>