jQuery UI Autocomplete With ASP.NET
In this post I want to show you how to integrate ASP.NET with jQuery UI Autocomplete widget. For those of you which don’t know what jQuery UI is here is a bit of introduction:
jQuery UI provides a comprehensive set of core interaction plugins, UI widgets and visual effects that use a jQuery-style, event-driven architecture and a focus on web standards, accessiblity, flexible styling, and user-friendly design.
From practitioner point of view – jQuery UI provides a few very nice and very useful widgets which you can really easily integrate with your application. Great example is Autocomplete widget which I will use in this post. I have found this widget very useful while implementing search functionality for my project. Of course to implement “just” search functionality where user can enter a keyword and click “search” button you don’t need much. And for sure you don’t need any fancy jQuery widgets. In my case additional requirement was to implement predictive search functionalty. That was a massive change for ASP.NET developer because out of the sudden I had to invoke search after each letter entered by a user and present it in a nice way.
Here is a great example how Google did the predictive search:

And here is another example, something like this I will show how to build in this post:

There is no component like that in Visual Studio! So the solution was to use jQuery UI Autocomplete widget.
How to integrate jQuery UI Autocomplete widget with ASP.NET
Step 1 – go to jqueryui.com and download jQuery UI. I was using version 1.8.14
Step 2 – include following JS scripts in your master page
<link href="/Styles/ui-lightness/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css" /> <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery-ui-1.8.14.js" type="text/javascript"></scrpt> <script src="/Scripts/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.position.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.autocomplete.js" type="text/javascript"></script>
On the list above are all jQuery, jQuery UI Autocomplete widget and dependencies. Please note that there is also CSS style on the list – this is required to make Autocomplete widget looks nice
Step 3 – Create a Web Service which will return predictive search results
[System.Web.Script.Services.ScriptService]
public class PredictiveSearch : System.Web.Services.WebService
{
[WebMethod]
public IList<string> GetAllPredictions(string keywordStartsWith)
{
//TODO: implement real search here!
// dummy implementation
IList<string> output = new List<string>();
output.Add(keywordStartsWith + "1");
output.Add(keywordStartsWith + "2");
output.Add(keywordStartsWith + "3");
output.Add(keywordStartsWith + "4");
return output;
}
}
This is an example of web service which returns dummy data. Your job is to take is further and integrate with your system. Good thing is that from this point it’s all .Net so something you should be comfortable with.
Step 4 – HTML Code
<div class="ui-widget">
<asp:Label ID="lblSearch" Text="Search" AssociatedControlID="txbSearchKeyword" runat="server"></asp:Label>
<asp:TextBox ID="txbSearchKeyword" runat="server" CssClass="searchinput"></asp:TextBox>
<asp:Button Text="Go!" runat="server" onclick="Search_Click" />
</div>
<asp:Literal ID="litStatus" runat="server"></asp:Literal>
As you can see HTML code is fairly straightforward. Only standard ASP.NET controls are here. Textbox txbSearchKeyword is the place where users will be entering keywords. So this is also the place where we need to add jQuery Autocomplete functionality. And that will happen in next step …
Step 5 – jQuery code
Firstly, let me show you the simplest possible implementation. It’s very simple so also a bit limited ![]()
Limitation in this case is that search results are static (there are no ajax calls to server for search results). This can work well in scenario where set of all possible options is very limited – for instance you can use it to tag content. Assumption is that set of tags is fairly constant and in total there are below 100 tags in the system.
$(document).ready(function () {
$(".searchinput").autocomplete({
source: ["test", "asp.net", "jQuery"],
minLength: 2
});
});
And here is an example which actually uses Web Service from step 3.
$(document).ready(function () {
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/PredictiveSearch.asmx/GetAllPredictions",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data){
response(data.d);
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
},
minLength: 2
});
});
In both examples searching for predictions will start not straight away after entering 1 letter! It will start after entering 2 letters, parameter minLength is responsible for that. You can see that behind the scene autocomplete functions calls our PredictiveSearch.asmx Web Service, in particular method GetAllPredictions(). In the next line we are passing entered letters as a parameter data.
It’s recommended to have your JS function in a separate file so that HTML code is separated from JS code.
Step 6 – Get Keyword on server side
On this stage, everything should be working now on client side. You should be able to see something this:

The only missing thing is implementation of onClick function called by “Go!” button. Implementation is again dummy, just to show you how to access all the relevant data:
protected void Search_Click(object sender, EventArgs e)
{
litStatus.Text = "Search conducted for keyword: " + txbSearchKeyword.Text;
}
And as far as I’m concerned this all what you need to integrate jQuery UI Autocomplete with ASP.NET. However here you will find more advanced tutorial showing how to customize jQuery UI Autocomplete widget.
Questions? If yes then leave a comment!
You can download the full ASP.NET project here with the jQuery UI Autocomplete integrated - it should help you with experimenting.
Hi, this is really useful post, thanks!
I was looking for a guide like this for a while, it’s nice to finally have all the information in one place
John Stone
14 Jul 11 at 8:44 am
I am using this code.
I have been wondering all around now for almost 8 hrs.
And still struggling, your code seems working atleast I am getting the exception
“Due to unexpected error we were unable to load the data.”
Any idea what is this???
Thanks
Jasin
25 Jul 11 at 6:45 pm
Hi Jasin – you can download the ASP.NET solution from this URL: http://jquery-with-asp.net/wp-content/uploads/2011/07/AutocompleteDemo.25.07.2011.zip
I hope it will help you to figure out what was wrong. If you will still have some issues – let me know.
admin
25 Jul 11 at 7:49 pm
Hi, Thank you for this demo project, I have tried this project and it is working, but it is now going above my patience…..
I have created a new 4.0 project in vs 2010, copied the web service, scripts and styles folder there, copied the markup from the given page in my new page, tested……………
Still nothing….
Unable even to get that exception message
Jasin
26 Jul 11 at 9:46 am
good one….
deepu
4 Aug 11 at 11:16 am
Very clear and informative. Works first time too which puts it way above most of the other examples I’ve found!
The only thing I’m struggling with is how to use this method with an external web service. Do you need to add the web reference and use that somehow in the ajax call?
thanks
Toby
1 Sep 11 at 12:01 pm
actualy – I found out how. I created a static webmethod in the calling page code behind and called the web service from there.
thanks again!
Toby
1 Sep 11 at 12:16 pm
It is working fine for , really good and helpful.
Sanjeev Gulati
2 Sep 11 at 1:29 pm
Use fiddler to see what error you are getting.I was also getting the error , but sorted by looking at the errors using fiddler.
Sanjeev Gulati
2 Sep 11 at 1:30 pm
I am using this widget and its working. MY requirement is to attach the Textbox to data from a webservice . Need to display two values for eg Company Name and Address in the Textbox and also when this is selected it should populate other fields on the page like City,Zip coming along from the webservice. Could anyone guide on this and I wann know if this widget is flexible with this kinda request
Muneeb
23 Sep 11 at 4:54 pm
Also I am formatting the values Company, ID,Address, Zip in JSON and returning back to Jquery from my webservice
Muneeb
23 Sep 11 at 4:57 pm
Thank! Saved me a lot of time and works 100%!
Shaun
18 Oct 11 at 10:30 am
Make sure you uncomment:
[System.Web.Script.Services.ScriptService] within the webservice.
Tedd
23 Oct 11 at 3:45 pm
Hi Muneeb – I have answered your question in the post about customization of jQuery UI autocomplete widget
admin
3 Jan 12 at 1:21 am
Hi
Fierst of all thank you for this useful post.
I am trying this sample in vs2008
i have done every thig according the post but nothing .
Unable even to get that exception message.
When i want to set CssClass of txbSearchKeyword to “searchinput” it shows a tip message that “class value dose not defined” .
i also aded :
to my page .
could you possibly help me ?
best regard .
mojtaba Shayanfar
21 Jan 12 at 1:16 pm
Hi,
Your code is working great. I have a question.
Is ‘word by word auto complete’ possible, similar to google search?
Eg: If I’m searching for “international tourism conference”,
when I start typing “international”, show the possible list start with that..
then, when I start typing the second word “tourism”, show the possible list.. etc..
Any suggestion or help would be appreciated.
Thank you
Robz
robz
1 Feb 12 at 1:53 am
Hi Robz! It’s of course possible, but you have to make server side logic slightly more complex.
If you want to show hints after full word, the easiest solution would be to to add space manually (if space is not the last character) and search for it. I would recommend also sorting results by relevance and this way show results which are most likely useful for your visitors.
admin
6 Feb 12 at 10:55 pm
great article! I was wondering if this can be set up so you can return an ID for each item in the list much like the jquery ui example? Thanks!
drew
12 Apr 12 at 7:33 pm
To amend my last question. I actually got this working. However, when I select an item it places the ‘value’ field into the textbox, instead of the ‘label’ which is the actually text the user types. I don’t want to replace the text with the id, have you run into this before? Any help is appreciated. Thanks!
drew
12 Apr 12 at 10:41 pm
Awesome search engine
yambis
15 Apr 12 at 11:47 pm
Hey first of all thank you for providing this demo and its working fine, but i just want to say that its providing auto complete suggestions really slow like its taking around 5-8 seconds to get changes reflected.. can you suggest some work arounds..
Ajeet Kulkarni
14 Jun 12 at 6:23 pm
Hey, solution presented here is basic solution which you can extend and add some sort of caching for instance to improve performance. It all depends how big you database is. How many combinations do you want to support? Depending on scenario you may want to 1) cache everything on server side, 2) cache only the most common queries 3) or do something more sophisticated and tailored to your needs.
Give me more details about your scenario then maybe I will be able to suggest something.
admin
14 Jun 12 at 8:06 pm
Thnx fo info, hey it wud be of great help if u could suggest me some cache technique in client or server side using this jq Ajax call so that it won’t query db always rather query from cache.. Coz I will be having 1000 of records as a returned results..
ajeet
14 Jun 12 at 8:17 pm
I will post something early next week,
Here is the promised post: http://jquery-with-asp.net/2012/06/how-improve-performance-autocomplete/
admin
14 Jun 12 at 8:19 pm
Thanks a lot.. I will be waiting..
ajeet
14 Jun 12 at 8:39 pm