We all know the need for having a autocomplete textbox in any web application. jQuery Tokeninput is one sucg jQuery plugin which allows your users to select multiple items from a predefined list, using autocompletion as they type to find each item.

Read Full Documentation from here.

Now lets integrate this plugin with our ASP.NET MVC 3 application.

Step 1 : Download !

Before reading any further, please download the plugin from here. Skip this step if you have already downloaded the plugin.

Step 2 : Unzip and Import !

Unzip the file downloaded and add the javascript file “jquery.tokeninput.js” to your solution as shown below.

Next up, import this js script to your view, I have added mine as shown below, and yes you also need to import jquery-1.5.1.min.js.

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/js/loopj/jquery.tokeninput.js" type="text/javascript"></script>    

Step 3 : How to write Jquery for this ?

First, we need to create a text field, Below is a text field that I have created for this example, note that my text-field has an id of “nameBox”.

This id will later be used in the jQuery TokenInput jquery call.

<p>
    Data from token input => <input type="text" id="nameBox" />
</p>

Here is the jquery call, which uses the id of the textbox we have defined above.

<script type="text/javascript">
    $("#nameBox").tokenInput("@Url.Action("SearchWithName")");
</script>

and here is how should write your action.

[HttpGet]
public JsonResult SearchWithName(string q)
{
    var searchResults = Helper.SearchContactByName(q);
    var jsonResult = searchResults.Select(results => new { id = results.Id, name = results.Name, city = results.City });
    return Json(jsonResult, JsonRequestBehavior.AllowGet);
}

Important Note (Source) : Your script should output JSON search results in the following format ONLY:

[
    {"id":"856","name":"House"},
    {"id":"1035","name":"Desperate Housewives"},
    ...
]

Now, lets run our application, you should get an output similar to the one shown below.

Output

Cheers !

Update : I have added a new post here, that show how to use **resultFormatter **with jQuery Tokeninput.

Update 2: We can change the default sent query param ‘q’ to say in the below used ‘searchTerm’ :

this.$("#abcTextbox").tokenInput("/Sports/GetAbc", {
    queryParam: "searchTerm"
});

Update 3: We can send extra param to the url using token input, as shown below :

this.$("#abcTextbox").tokenInput("/Sports/GetAbc?someParam1=cricket&someParam2=yasser", {
    queryParam: "q"
});