Saturday, September 17, 2016

Using Bootstrap Typeahead.js Plugin in an ASP.NET MVC Project

Hello all,

Bootstrap has lots of plugins that you can experiment with, and one of them is the Typeahead.js plugin similar to jQueryUI Autocomplete plugin. According to Bootstrap, Typeahead is an extendend plugin for quickly creating elegant typeaheads with any from text input.

So given the description of the widget, I will provide a tutorial that integrates the plugin in an ASP.NET MVC project basing from this article Twitter Bootstrap Typeahead and ASP.NET MVC. The author from the source demonstrates preloaded country values but in my case, I modified it to handle searching through a database.

So to proceed with, just follow the steps below:
1. Create an ASP.NET MVC Project (C#).
2. Add an ADO.NET Entity model that connects to the AdventureWorks DB and it's CountryRegions table.
3. In your home controller, add the code that search countries based on a given value.
private static AdventureWorks2012Entities _context;

//
// GET: /Home/
public ActionResult Index()
{
 return View();
}

[HttpGet]
public JsonResult GetCountries(string query)
{
 _context = new AdventureWorks2012Entities();

 var result = (from country in _context.CountryRegions.AsEnumerable()
      where country.Name.ToLower().Contains(query)
      select country.Name);

 return Json(result.ToArray(), JsonRequestBehavior.AllowGet);
}
4. In the head section of Index View, add reference to typeaheadjs.css and bootstrap3-typeahead.js files.
<link href="~/Content/typeaheadjs.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap3-typeahead.js"></script>
5. Add the script to utilize the typeahead.js plugin for searching data.
$(document).ready(function () {

  $("#Countries").typeahead({
   source: function (query, process) {
    var countries = [];
    map = {};

    // This is going to make an HTTP get request to the controller
    return $.get('/Home/GetCountries', { query: query }, function (data) {

     // Loop through and push to the array
     $.each(data, function (i, country) {
      map[country] = country;
      countries.push(country);
     });

     // Process the details
     process(countries);
    });
   },
   updater: function (item) {
    var selectedCountry = map[item];

    // Set the text to our selected id
    $("#details").text("Selected : " + selectedCountry);
    return item;
   }
  });
 });
6. In the body section, just add a div element and an input element that will trigger the typeahead event.
<div id="details" class="row"></div>
<div class="row">
 <input type="text" id="Countries" class="form-control" placeholder="Counry Name" />
</div>
Screenshot
ASP.NET MVC VB.NET Version here.

That's it.. :-)

0 comments:

Post a Comment