Wednesday, January 26, 2011

autocomplete

autocomplete is one the coolest features for a UI to have.So i happened to get a chance to make it.I had some struggle initially as i am new to jquery but finally got it and it works like a charm.

To do this you need to download Jquery autocomplete bundle.So,all we need to do is when the document loads we need to do a ajax call to your action to get your results(which is coming from your database or file,etc).For me it is the database,so you want to play around with it to find a sweet spot where your UI is not getting a performance hit because your query is taking too long.

jQuery(document).ready(function() {
$.ajax({
type: "GET",
url: "controller/AutoComplete",
data: '{}',
success: function(msg) {
// Do something interesting here.
if (msg != null) {
data = msg.toString().split(",");
$("#Name").autocomplete(data);
}
},
error: function(xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server
alert(err.Message);
}
});
}); 



Now in your action,you need to call your repository to return back results,here i am returning a comma seperated array which i spit it and feed to the the autocomplete script.


[HttpGet]
public ActionResult AutoComplete()
{
string model = repository.GetDistinctNames();
return Content(model);
}

That's it you see autocomplete feature in your UI and your clients will be happy.