Jun 21, 2012

Using jQuery UI Autocomplete With ASP.NET Web API

It explains how to implement jQuery UI Autocomplete feature with ASP.NET Web API and Entity Framework DB First approach. Suppose you have to display complete information of user selected item from auto-complete textbox. In this case you might need primary key field of selected item means we've to get Id and Name both from Web API.

We'll use Artist table of MVC Music Store database. Assuming all names are unique and we have to include ArtistId also with Name as response of Web API action.


Create Project:

Here are the basic steps to create Web Api project and add entity data model for Artist table.

1. Open Visual Studio > File > New > Project

2. Select "ASP.NET MVC 4 Web App" > OK

3. Select "Web API template" > OK

4. Right click on Models > Add > New Item

5. Select "ADO.NET Entity Data Model", Enter Name

6. Generate From Database, Select Database > Next

7. Select Tables and related Stored Proc > Finish

Web API Action:

Open ValueController.cs and add Get method which takes term as string argument and returns dictionary of ArtistID and Name as below:

public IDictionary<int,string> Get(string term)
            using (MVCMUSICSTOREEntities context = new MVCMUSICSTOREEntities()) {
                return context.Artists.Where(x => x.Name.Contains(term)).ToDictionary(x => x.ArtistId, x => x.Name);    

If you check in firebug console, you will get following response:


If you want the result must be start with user entered keyword then use StartsWith instead of Contains.

return context.Artists.Where(x => x.Name.StartsWith(term)).ToDictionary(x => x.ArtistId, x => x.Name);    


For simplicity, We'll consume above action in same project. Delete existing Views > Home > Index.cshtml file and in HomeController.cs, Right click on Index action > Add View> uncheck all options > Add.

Now first step is to add CSS and script files of jQuery, jQuery UI.

    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    @Scripts.Render("~/bundles/modernizr", "~/bundles/jquery", "~/bundles/jqueryui")


You can include file like this:

<script src="~/Scripts/jquery-1.6.2.min.js" type="text/javascript"></script> 

Here is the auto-complete feature implementation:

 Search : <input type="text" id="txtSearch" />
    <script type="text/javascript">
            $(function () {
                    source: function (request, response) {
                            url: '/api/values',
                            type: 'GET',
                            cache: false,
                            data: request,
                            dataType: 'json',
                            success: function (json) {
                                // call autocomplete callback method with results  
                                response($.map(json, function (name, val) {
                                    return {
                                        label: name,
                                        value: val
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                //alert('error - ' + textStatus);
                                console.log('error', textStatus, errorThrown);
                    minLength: 2,
                    select: function (event, ui) {
                        alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
                        return false;

On typing min two characters, Ajax request is made to call web api action, the response is converted in label:'...',value:'... ' format (It's the main tricky part) and list is displayed. When you select any item, it is displayed with Id in alert box.


Hope, It helps.