Carl Hörberg on development

Microsoft has swifted away from Ajax Library and they are promoting jQuery as the primary way of develop client side ajax applications. This is good news, Microsoft is even contributing resources to the jQuery core team.

A couple of weeks ago i showed how you could use Ajax Library Autocomplete component with Asp.Net MVC. This time I will instead show you how to make the new Autocomplete component in jQuery UI 1.8 play well with Asp.Net MVC, and it's a lot easier than with Ajax Library!

First, in your view, include jQuery 1.4 and jquery UI 1.8 (here i use Google's javascript CDN), then add a text field to your body, then some javascript to hook it up:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class AutocompleteController : Controller
{
private readonly IRepository db;
public AutocompleteController(IRepository db)
{
this.db = db;
}
 
public JsonResult Users(string term)
{
var data = db.Query<User>()
.Where(r => r.Name.StartsWith(term))
.Select(r => new { r.Id, value = r.Name })
.Take(10)
.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/cupertino/jquery-ui.css" type="text/css" rel="Stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
<input type="text" name="completeMe" id="completeMe" />
<script type="text/javascript">
$(function() {
$("#completeMe").autocomplete({
source: '/Autocomplete/Users',
minLength: 1,
select: function(event, ui) {
// Do something with "ui.item.Id" or "ui.item.Name" or any of the other properties you selected to return from the action
}
});
});
</script>
</body>
</html>

I've included the select event, which will fire when the users has selected an item, in which you can load more stuff etc. Be sure to check out the API for autocomplete for more events and properties.

If you look at the Autocomplete controller you see that I query my User table where the Users name starts with the incoming term. We select only the id and the name from the user (you can select more stuff if you want to make it available in your jQuery events). I only take 10 items, make an array of them which we return as Json.

Important to note is that we have to add "JsonRequestBehavior.AllowGet" argument to the Json() function because jQuery UI Autocomplete makes a Get request and Asp.Net MVC by default doesn't allow this because of the security concerns.

 
blog comments powered by Disqus