Coding Tips & Tricks


Home > JavaScript

Twitter bootstrap typeahead and ASP.NET MVC - Key/Value pairs

I suck at creating CSS. As a backend developer, I've always managed to get by with my CSS skills, but I've always been jealous of my front end developer colleagues when it comes to their ability to create beautiful web pages. Fortunately, the guys at Twitter have developed a great front-end framework that comes with pre-rolled CSS and JavaScript plugins.

Twitter Bootstrap typeahead searchbox

The Twitter Bootstrap framework looks great on most devices and comes with a responsive grid which makes developing and designing very easy. It gives back-end developers like myself the opportunity to create half decent webpage designs. I have actually been using it on a recent side project when I came across the JavaScript typeahead plugin that comes with the framework. It is a great plugin that allows you to create styled AJAX style, type ahead search boxes.

Twitter Bootstrap typeahead searchbox key/value pairs

The image above represents a typical example of how the search box will look. The Bootstrap website provides great documentation for most of the framework, but seems to provide little documentation for this particular plugin. Whilst it's very easy to work with a simple list of strings, the few examples that I found on the net didn't really show how to work with Key/Value pairs. Most searches that I need to perform will require an ID lookup going on in the background. In this post, I am going to show you how to get up and running with ASP.NET MVC and the typeahead plugin. We are also going to get it working with key/value pairs that are being retrieved in a chunk of JSON from an MVC controller.

If you haven't already downloaded the Twitter Bootstrap framework, get started by downloading it from the site. Next, we are going to start with our view. I've created a simple view with a textbox that is going to do the lookup.

At the bottom of the view, I've included a reference to the jQuery library and the typeahead plugin. I've added the JavaScript at the bottom of the page in order to maintain performance best practices. At the top of the view, I've added a reference to the Bootstrap CSS file which is used to style the page.

You will also notice that the text box has a data attribute called data-provide="typeahead". This attribute notifies the plugin that we are going to be performing a lookup with this textbox. Next, we are going to create the JavaScript that will wire it all up. Add this code into the same view just after referencing the Bootstrap libraries.

The above code is going to perform an HTTP Post request that is going to hit our controller and return a JSON string of the countries and their associated codes. On line 3, I have created an array that is going to contain the key/value pairs. Once the HTTP post has a successful response with the data that it needs, it is going to add them to this array, so that we can retrieve it at a later stage. You will also notice that around line 16, there is a function called "process". This function takes the array of results and searches through according to what the user types.

This typeahead plugin has a set of overridable options that can be used to cater for different scenarios when interacting with the lookup. We are going to use the "updater" function in this example. This function is called by the typeahead plugin once the user selects an item, which gives us a chance to do something with the selection. On line 19, we are using this function to retrieve the country shortcode from the array of key/value pairs that we mapped earlier. We are also setting the text of a div to match the shortcode. Depending on what you need to do with the key, you might want to set the value of a hidden field, update another field, etc.

We have built all the JavaScript that is needed to retrieve the data, and now we need to add an Action method on our controller that will return the JSON string of the countries.

The above code builds a list countries with a short code and country name. This list will be serialized into the JSON string that we need to do the lookup. Once serialized, the JSON string that it returns will look a little something like this:

[{"ShortCode":"US","Name":"United States"},{"ShortCode":"CA","Name":"Canada"},{"ShortCode":"AF","Name":"Afghanistan"},{"ShortCode":"AL","Name":"Albania"},{"ShortCode":"DZ","Name":"Algeria"},{"ShortCode":"DS","Name":"American Samoa"},{"ShortCode":"AD","Name":"Andorra"},{"ShortCode":"AO","Name":"Angola"},{"ShortCode":"AI","Name":"Anguilla"},{"ShortCode":"AQ","Name":"Antarctica"},{"ShortCode":"AG","Name":"Antigua and/or Barbuda"}]

Although I am simply building up a list of countries, you might want to hit the database and return more meaningful data. When we run this and see it in action, it will produce a search bar that is similar to the following image:

Twitter Bootstrap typeahead searchbox key/value pairs

And once you select a certain country from the list, it will update the div with the selected ID accordingly.

Twitter Bootstrap typeahead searchbox selected

For more information on the Twitter Bootstrap plugin, check out the website. If you would like to learn more about the overridable functions that the typeahead plugin provides, please refer to this great blog post.








Comments

Gary Woodfine - 4/5/2013
Great article Dean. Very easy to read, and got me up and running in no time! Great to see your UI skills being improved! maybe one day you'll move away from the eye straining yellow background on your code snippets :-) Keep up the good work, look forward to your next article

Rodrigo - 4/8/2013
Is a nice solution, but when you have duplicity on the column name this solution will fail. I hope you know that...

Dean Hume - 4/8/2013
@Rodrigo Thank you. Yup, this will need to be catered for and code updated in the case of duplicate column names. It could possibly be updated when the server returns the data.

Jay - 4/11/2013
looked everywhere for this. great post. saved me hours!

Dean Hume - 4/12/2013
@Jay - Thanks - glad it helped!

zoidberg - 4/15/2013
i am getting the error: Uncaught Error: one of local, prefetch, or remote is required jquery-1.9.1.js:507 i am using typeayhead 0.9.1 (Nuget-Package)

Jason S - 5/30/2013
Thanks for this simple and direct walk-through. Helped me a bunch!

George - 6/20/2013
Hi Dean, This worked great for me using IIS express in VS 2012 but a failed to load countrylookup in the javascript console in IIS. Any thoughts?

Dean Hume - 6/30/2013
@George - Are you able to open up a network console in your browser and provide the details? Regards Dean

emre - 3/25/2014
I am getting Cannot call method 'hasOwnProperty' of undefined error


Add your comment

300 Characters left


Please fill this in to confirm that you are human