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:
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
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:
@Scripts.Render("~/bundles/jquery")
@Styles.Render("~/Content/themes/base/css")</pre>
NOTE 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:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
Now you need to add code that implements the autocomplete. Firstly, place a label and a text box in the page you wish. For this example, I will go ahead and place it inside index.cshtml
<div class="ui-widget">
<label for="results">Results:</label>
<input id="results"/>
<button type="button" id="#btnGo">GO</button>
</div>
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:
<script type="text/javascript">
var url = 'http://localhost:62615/api/addresses'; /*this can be any webservice*/
$(document).ready(function() {
$('#results').autocomplete({
source: function(request, response) {
$.ajax({
url: url,
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
};
}));
}
});
},
minLength: 1,
select: function(event, ui) {
/*alert(ui.item.label + " - " + this.value);
*/
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
</script>
Let's break this down so that we can see what’s happening:
$('#results').autocomplete({ ....
This code is the key that turns our textbox to an autocomplete text box.
source: function(request, response) {
$.ajax({
url: url,
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
};
}));
}
});
},
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".
minLength: 1,
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.
select: function(event, ui) {
/*alert(ui.item.label + " - " + this.value);
*/
},
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.
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
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…