MVC 4.0: Autocomplete with jQuery UI

mvc

Autocomplete is a very nice feature that makes your website more responsive to user inputs. I like this feature very much 🙂

Before you use autocomplete, you can set up the application to include the base theme style sheet by adding it to the layout view:


<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

You’ll need to fi nd the input element from JavaScript and attach the jQuery autocomplete behavior. One approach to do this is to borrow an idea from the MVC framework and use a data dash attribute:


<input type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Home")" />

Note that you’ve pointed the source to a controller action.

You can use the following code during the ready event to attach autocomplete to all inputs with the data-autocomplete-source attribute:


$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({ source: target.attr("data-autocomplete-source") });
});

Autocomplete expects to call a data source and receive a collection of objects it can use to build a list for the user. The QuickSearch action of the HomeController needs to return data in a format autocomplete will understand.

Autocomplete expects to call a data source and receive objects in JSON format. Fortunately, it’s easy to generate JSON from an MVC controller action, as you’ll see soon. The objects must have a property called label, or a property called value, or both a label and a value. Autocomplete uses the label property in the text it shows the user. When the user selects an item from the autocomplete list, the widget will place the value of the selected item into the associated input. If you don’t provide a label, or don’t provide a value, autocomplete will use whichever property is available as both the value and the label.

To return the proper JSON, you’ll implement QuickSearch with the following code:


public ActionResult QuickSearch(string term)
{
var artists = GetArtists(term).Select(a => new {value = a.Name});
return Json(artists, JsonRequestBehavior.AllowGet);
}
private List<Artist> GetArtists(string searchString)
{
return storeDB.Artists
.Where(a => a.Name.Contains(searchString))
.ToList();
}

You are ready to run your application now, you should have something like the following:

autocomplete

Thank you 🙂

Keep It Simple & Straightforward.

~:H}{H:~

 

2 thoughts on “MVC 4.0: Autocomplete with jQuery UI

  1. Nice post…… keep up the good work!…

Leave a reply to Mohamed Radwan Cancel reply