Its always fun to try new things and especially when it takes repeated trials, the more exciting it gets 
I must tell you it was a very exhaustive day for me to keep trying. So, I thought it’s worth sharing it. Before we begin, if you are new to jQuery, Oh! it’s awesome. It’s the most popular JavaScript Library in use today. It’s worth spending some time at http://jquery.com/
jQuery is a new kind of JavaScript Library.
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
http://jquery.com/
If you are new to MVC, just google it, you will get tons of information. However, for .NET MVC 2.0, here are some pointers;
Let’s begin our topic of discussion “jQuery-Autocomplete”, small but powerful and very useful plugin that we see in almost every website or we wish we had one. JQuery has an extensive list of plugins available. http://plugins.jquery.com/
The basic idea is, we have one website say “Media Library”, and user wants to search the songs and as a smart user
we would like to search them as we type 
Yes the answer is Autocomplete, in ASP.NET AJAX or similar other libraries you would have seen or used the same. Here we are going to use this while we build a small website in ASP.NET MVC using jQuery. Here the plugin adds necessary behavior to handle key press events etc.
Tools that I am using:
Create a ASP.NET MVC 2 Web Application
Note: Use the template that is provided with Visual Studio that will create all the skeleton that is required for the MVC project
Download the Plugin Scripts from
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
http://docs.jquery.com/Plugins/Autocomplete (you may please refer for complete documentation)
Scenario 1: Let’s say our songs data is static data
Add references of CSS and scripts as below to the page
1: <link href="<%= Url.Content("~/Content/jquery.autocomplete.css") %>" rel="stylesheet" type="text/css" />
2: <script src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>" type="text/javascript" />
3: <script src="<%= Url.Content("~/Scripts/jquery.autocomplete.js") %>" type="text/javascript" />
Add one text box
1: <input type="text" id="txtSongsStatic" />
The below script
1: //Static data for autocomplete
2: var songs = ['Aaj Rani Poorvichi Ti Preet', 'Aaj Tula Javalun Pahaiche Ahe', 'Aala Aala Paus Aala', 'Aala Aala Wara'];
3:
4: $(document).ready(function () {
5: //Adding autocomplete to region input
6: $("#txtSongsStatic").autocomplete(songs);
7: });
That’s it?
yes that’s it and you will see a cool autocomplete working for you as shown below
Here autocomplete plugin has lots of interesting options which you may try it out
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
But life is not always that simple
, as our data in 99% of cases is not static. Let’s make it little complex where our data is stored in database.
Note:
Ensure that the browser you are using supports viewing the requests and responses headers and contents as shown in the below image. This is very important when you are working with any ajaxified application. Otherwise trust me you will spend your whole day in finding the problem and yet you won’t
For Google Chrome it’s built in browser just press Ctl + Shit + I or Go to Developer –> Developer Tools
For Internet Explorer we have Web Development Helper
For Firefox we have Firebug
Likewise, you may find one for your favorite browser
Scenario 2: Data is dynamic and is stored in Simple Database “MyMedia” with one simple table “Songs” as shown in image below
So now your html will look like
1: Search Songs [Static]:
2: <input type="text" id="txtSongsStatic" />
3: <br />
4: Search Songs [Dynamic]:
5: <input type="text" id="txtSongsDynamic" />
And your script will be
1: //Static data for autocomplete
2: var songs = ['Aaj Rani Poorvichi Ti Preet', 'Aaj Tula Javalun Pahaiche Ahe', 'Aala Aala Paus Aala', 'Aala Aala Wara'];
3:
4: $(document).ready(function () {
5: //Adding autocomplete to region input for static data
6: $("#txtSongsStatic").autocomplete(songs);
7: //Adding autocomplete to region input for dynamic data
8: $("#txtSongsDynamic").autocomplete('<%=Url.Action("GetSongs", "Home") %>', {
9: dataType: 'json',
10: parse: prep_data,
11: formatItem: format_item
12: });
13: });
14: prep_data = function (data) {
15: parsed_data = [];
16: for (i = 0; i < data.length; i++) {
17: obj = data[i];
18: // Other internal autocomplete operations expect
19: // the data to be split into associative arrays of this sort
20: parsed_data[i] = {
21: data: obj,
22: value: obj.Id,
23: result: obj.SongTitle
24: };
25: }
26:
27: return parsed_data;
28: }
29: format_item = function (item, position, length) {
30: return item.SongTitle;
31: }
In this case, instead of using the static array we are using an asynchronous call to server. At the server side we have a controller Home and action as GetSongs, where this function is going to dump JSON and that will become the source to the autocomplete.
1: public ActionResult GetSongs(string q)
2: {
3: MyMediaDB mediaDB = new MyMediaDB();
4: var songs =
5: from song in
6: mediaDB.Songs
7: where
8: song.AlbumName.Contains(q) ||
9: song.ArtistName.Contains(q) ||
10: song.SongTitle.Contains(q)
11: select
12: song;
13:
14: return Json(songs.ToList(), JsonRequestBehavior.AllowGet);
15: }
One Very Important Note here
Look at return Json(songs.ToList(), JsonRequestBehavior.AllowGet);
Sometimes you may receive an error whenever you execute a json request "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."
The reason is, in MVC 2 they block Json for GET requests (as you can tell from the error) for security reasons. If you want to override that behavior, check out the overload for Json that accepts a JsonRequestBehavior parameter.
This can happen only in case if by mistake you do not use AllowGet
For Example, in the below case you may receive an error,
return Json(songs.ToList());
One last note here, unless you use those small browser plugins (I have explained above) that shows the requests, responses, their header, contents, it will be very difficult to trace the problems.
That was about the server side, now let’s discuss the client side code where we are calling autocomplete. Here we are using three options of the autocomplete function
However, parse option is undocumented (as far as I know ) and this is where i stumbled for some time and finally it worked for me. We can use this option when we want to use data that doesn’t fit autocomplete’s assumptions.
For Example: If our data is not just key-value (Item-Value) pair, it’s our own class and from this we would like to use some field as value/display then this is where this option comes handy, where we can supply our own function to parse our collection in a way autocomplete can understand. Here in our example we have our own collection as songs and we want to display SongTitle.
Finally, you see the result like this

You can download the complete source code from here
Features like autocomplete can be great saviour when your data is large and users have to select from the them. This also helps in keeping the page size as light as possible. Sometimes you may provide multiple search criteria. For Example in our case, user can search songs based on song title, album name, artist name etc. Such features can create great user experience on your website.
Hope this helps you get web apps looking cool.
Additional Reference
http://en.wikipedia.org/wiki/JQuery
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
http://docs.jquery.com/Plugins/Autocomplete
http://flux88.com/blog/jquery-auto-complete-text-box-with-asp-net-mvc/
http://tpeczek.blogspot.com/2010/05/jquery-autocomplete-in-aspnet-mvc.html
http://www.barneyb.com/barneyblog/2008/11/22/jquerys-autocompletes-undocumented-source-option/
In case if any reader finds any information is wrongly said/written on my blog please do write me @bharat.mane@gmail.com
If you find these to be helpful, be sure to drop me a note in comments.
Hope you enjoyed it!
Recent Comments