Categories
Uncategorized

Using resultsFormatter in jQuery Tokeninput with ASP.NET MVC 3 Razor

This is in continuation on my previous post, where I had explained how to setup and use the jQuery Tokeninput. In this article, I will be showing you how to use the ‘resultsFormatter’ function.

resultsFormatter is a function that returns an interpolated HTML string for each result. Use this when you want to include images or multiline formatted results.

Jquery

$("#selectCity").tokenInput("@Url.Action("
SearchWithCity ")", {
propertyToSearch: "name",
resultsFormatter: function(item) {
return "<li>" + item.name + " - <i>" + item.city + "</i>" + "</li>";
},
});

and here is my controller action ‘SearchWithCity’…

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

When you run this code, below is the output you should get.


It is as simple as this, you can include all html tags to customize your search results.