jQuery UI – Autocomplete in MVC

jquery-ui-autocomplete-01

jQuery UI offers a lot of nice features, one of those is autocomplete drop downs. These are especially helpful when you have a data entry field that people need to lookup values from a long list for, or often use the same values for.

Let’s jump right in, in their simplest form, you need a couple things… A form field, some javascript and some CSS. I’ll be using jQuery for everything, since this is the jQuery UI we’re talking about.

 

The Form

First start out with your form. I’m using bootstrap for layout, etc. Here is the plain HTML, followed by an MVC example.

<form action="" method="post">
<div class="row">
	<div class="col-xs-12 col-sm-4">
		<div class="form-group">
			<label for="MyAutocomplete">My Autocomplete:</label>
			<input class="form-control" id="MyAutocomplete" name="MyAutocomplete" type="text" value="" autocomplete="off">
		</div>
	</div>
</div>
</form>
<form action="" method="post">
<div class="row">
	<div class="col-xs-12 col-sm-4">
		<div class="form-group">
			<label for="MyAutocomplete">My Autocomplete:</label>
			@Html.TextBoxFor(model => model.MyAutocomplete, new { @class = "form-control" })
		</div>
	</div>
</div>
</form>

 

The Controller

Once you have the basic form and input setup, next is to create your method that the autocomplete will call to get a list of values to show as the autocomplete list.

public class MyAutcompleteController : Controller
{
	[HttpPost]
	public JsonResult MyAutocompleteValues(string term) {
		string[] results = MyAutocomplete.GetAutocompleteValues(term) ?? new string[] { };
		return Json(results.Select(x => new { label = x, ID = x }));
	}
}

In this instance, my MyAutocomplete.GetAutocompleteValues would return a list of strings from a database or whatever source you are planning to use to get your values from. If it’s a fixed list of values, you can do something simple like the following example that reads from a string array and returns values that start with the search term sent by the autcomplete javascript.

public class MyAutcompleteController : Controller
{
	[HttpPost]
	public JsonResult MyAutocompleteValues(string term) {
		string[] terms = new string[] { "0400", "0401", "0402", "0403" };
		return Json(terms
			.Where(x => x.StartsWith(term, StringComparison.CurrentCultureIgnoreCase))
			.Select(x => new { label = x, ID = x }));
	}
}

 

The Javascript

Now that we have our method for returning the autocomplete list of values, we can wire that up to our javascript.

$(document).ready(function () {
	$("#MyAutocomplete").autocomplete({
		source: function (request, response) {
			// call your Action
			$.ajax({
				url: "/MyAutocomplete/MyAutocompleteValues",
				type: "POST",
				dataType: "json",
				data: { term: request.term },
				success: response
			});
		},
		minLength: 1, // require one character from the user
		select: function (event, ui) {
			// set the selected value
			$(this).text(ui.item.value);
		}
	});
});
For more details about what options are available with the jQuery UI Autocomplete and more examples, check out http://api.jqueryui.com/autocomplete/.

Using a jQuery selector, you can pick the form field, wire up the autocomplete, and jQuery does the rest for you. If you have a bunch of autocomplete lists you want to use you can assign a CSS class to the form fields and reference them by the CSS selector, $(“.autocomplete”).autocomplete(…). That will wire up everything with a CSS class of “autocomplete”.

 

Putting it all Together

Here is all of the html/css/javascript together, all you need is to set up your controller and change the URL in the jQuery AJAX call.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>My Autocomplete</title>
	<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
  <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>

	<form action="" method="post">
		<div class="row">
			<div class="col-xs-12 col-sm-4">
				<div class="form-group">
					<label for="MyAutocomplete">My Autocomplete:</label>
					<input class="form-control" id="MyAutocomplete" name="MyAutocomplete" type="text" value="" autocomplete="off">
				</div>
			</div>
		</div>
	</form>

	<script type="text/javascript">
	$(document).ready(function () {
		$("#MyAutocomplete").autocomplete({
			source: function (request, response) {
				// call your Action
				$.ajax({
					url: "/MyAutocomplete/MyAutocompleteValues",
					type: "POST",
					dataType: "json",
					data: { term: request.term },
					success: response
				});
			},
			minLength: 1, // require one character from the user
			select: function (event, ui) {
				// set the selected value
				$(this).text(ui.item.value);
			}
		});
	});
	</script>
	
</body>
</html>

Leave a Reply

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