jQuery
.NET, Blog, Software Development, Web Development

jQuery UI Autocomplete with jSON in MVC 4

jQueryUi has an autocomplete plugin that allows developers to turn any standard text box to turn any standard textbox to an autocomplete search box. In this case we will try to implement this in the simplest way possible using a web service as the data source.

First of all, create a standard MVC 4 project. This will be used to test our functionality, however any existing website can be used for the same purpose. If you are not already referencing the jQuery and jQuery UI libraries in your _layout.cshtml, add them. You can either add them directly in your code using the old-fashioned way:

Alternatively, if you are like me, you can use the the bundling functionality and create the appropriate bundles and add them using the commands below:

Note that I prefer to bundle my jQuery and jQueryUI together for simplicity but it is totally up to you how you chose to bundle your libraries and css. My BundleConfig.cs class looks like this:

Now you need to add code that implements the autocomplete. First place a label and a text box in the page you wish. In this case, I will go ahead and place it inside index.cshtml

The code above creates a label, a textbox and a button. Ignore the button for now! Next you need to add the necessary code that implements the autocomplete functionality such as search and result parsing. At the bottom of the same page, add the following code segment:

Let’s break this down so that we can see what’s happening:

This code is the key that turns our textbox to an autocomplete text box.

The code above provides the data for our textbox. The source parameter takes a function which in turn performs an ajax query to the url we defined earlier. In this example, the url points to a local WebApi webservice that returns a list of addresses. Upon success, the response object is parsed into an array which populates the drop down with a set of labels and values. The label is what you see in the drop down list and the value can be the same or another value from the returned results. In this case I decided to keep these two values the same, i.e “item”.

The minLength property determines at which stage to kick off the call to the web service. If set to 1 the call will be executed after the first character is typed in the textbox. If set to 3, then the call will be initiated after the 3 character is typed.

The select property allows to execute custom methods. In the example above I chose to display an alert box with the values of the selected option.

As with the select property, the open and close properties allow us to add custom operations when the drop down list box is opened and closed.

This is more or less the code needed to implement a basic autocomplete textbox with webservices as the backend data source. More details about the full plugin documentation can be found here

Happy coding…

Standard