Using Twitter typeahead.js with ASP.NET MVC Web API

There are many auto-complete jQuery libraries I have used before, like jQuery UI’s Autocomplete, loopJ’s jQuery Tokeninput and Select2. But one of my colleague at work, recently introduced me to this jQuery plugin called twitter’s typeahead.js, it seemed to be good, so we decided to use it in one of our ongoing project.

So, What is typeahead.js ? typeahead.js is a fast and fully-featured autocomplete library. You can check out some of the basic examples from here or you can hit straight to the docs from here.

Lets get started with a few basic examples.

1. Things you’ll need to download: You can download the latest version of typeahead.js from here. Below are the js and css you’ll need to include :

<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.js" />
<link href="http://twitter.github.io/typeahead.js/css/examples.css" rel="stylesheet" />

2. Local data example: (fiddle)

<input type="textbox" placeholder="Search Song" id="search-box" />

<script type="text/javascript">
$('input#search-box').typeahead({
  name: 'name',
  local: ['yasser', 'shyam', 'sujesh', 'siddhesh', 'vaibhav']
});
</script>

typeAhead-local

3. MVC Web Api example :

public class SongController : ApiController
{

    public JsonResult GetSongs(string searchTerm)
    {
        List<Songs> songList = new List<Songs>();
        songList.Add(new Songs{ Name = "Addat", Artist = "Aatif Aslam", Year = "2007"});
        songList.Add(new Songs{ Name = "Woh Lamhey", Artist = "Jal - The band", Year = "2008"});
        songList.Add(new Songs{ Name = "Kryptonite", Artist = "3 Doors Down", Year = "2009"});
        songList.Add(new Songs{ Name = "Manja", Artist = "Amit Trivedi", Year = "2013"});
        songList.Add(new Songs{ Name = "Tum hi ho", Artist = "Arjit Singh", Year = "2013"});

        songList = songList.Where(m => m.Name.Contains(searchTerm)).ToList();

        return songList;
    }
}

public class Songs
{
    public string Name { get; set; }
    public string Year { get; set; }
    public string Artist { get; set; }
}

$("#search-box2").typeahead({
    name: 'songs',
    valueKey: 'Name',
    remote: {
        url: '/Song/GetSongs?searchTterm=%QUERY'
    }
}); 

Hope this helps :)

About Yasser Shaikh

Hello, I am a Web Dev, employed with Media.Net where I primarily work on ASP.NET MVC and Angular JS based developement.

Questions? Enquiries? Comments? Or even just want to say “Hi” to me, you are welcome to all of that. Just drop me a message at "mail@yassershaikh.com" and I’ll get back to you as soon as possible.

Cheers !