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 :)

  • Paul Custance

    Thanks for the article. How would you go about posting the selected value back to the controller?

    • yassershaikh

      the query /Song/GetSongs?searchTerm=%QUERY’ will find a controller named “Song” and an action named “GetSongs” which accepts a input paramter “searcTerm”

      • Paul Custance

        Great I’ll give this a go. I was more thinking about once the user has made a selection in the typeahead, how is the selected value bound to the control? So lets says I have the following data Songs = ({ Name = “Applause” Track = 1}, { Name = “Iris” , Track = 2})

        I would want the typeahead to show the values, “Applause” and “Iris” but when one is selected the track is the value bound to the control and hence submitted back to the server once the user submits the page.

        Any help greatly appreciated! There is very little info on the web for using the Twitter Typeahead (vs Bootstrap Typeahead). Perhaps you could expand upon your original post?

        Thanks

        • yassershaikh

          Do you want to get the selected value from typeahead when the use selects it or presses enter after typing in the search query ?

          This should help

          this.$(“input#search-box”).bind(‘typeahead:enterKeyed’, function (e, data) {
          // do your stuff here
          var searchValue = this.$(“input#search-box”).val()
          });

  • http://jonathanpeterson.com Jonathan Peterson

    what does the the response look like at

    “/Advertiser/GetSongs?searchTterm=a” ?

    • yassershaikh

      see once the search term reaches the controller the way you search is upto to… you want a case to case match, typeahead match you have to write logic according to that.. as far as the above code is concerned, the query will return “Addat, Woh Lamhey and Manja” since I have used m.Name.Contains(searchTerm).

      Hope this helps

      • http://jonathanpeterson.com Jonathan Peterson

        I mean what does the JSON you are returning look like?

        • yassershaikh

          see I am returning a list of a type, here type is my class ‘Songs’, so the json returned in the above case will be something like

          [{ Name = "Addat", Artist = "Aatif Aslam", Year = "2007"}, {}, {}]