AutoComplete Textbox using Twitter Bootstrap TypeAhead jQuery Plug-in and Web API - C# and Vb.Net

← PrevNext →

AutoComplete, sometimes known as TypeAhead, is a feature that displays a set of results based on a single and sometimes multiple character input. There are many AutoComplete jQuery plug-in on the web today and Twitter too has authored a flexible and robust JavaScript library called the typeahead.js, which provides AutoComplete search functionalities. Here in this article I am going to show you how to use typeahead.js for AutoComplete using jQuery Ajax and Web API.

Twitter Bootstrap TypeAhead Ajax Example

You can find some examples here. They have shared an example with the open source community using some basic features to retrieve or extract data from a Client source (JSON). However, in this article I am using jQuery Ajax to extract data from a remote SQL Server table with the help of a Web API Controller.

What we need for this example?

I only have one input box element of type text on my web page. I’ll attach the input box with the jQuery typeahead() method provided by the library. When the user types a character in the textbox, the typeahead() will make an Ajax call to the Web API Controller, which will fetch data from the table based the character input and return list. The TypeAhead UI view will render the data and display it just below the textbox like a drop down list.

I have already created the SQL Server table that will provide the data for the search query. Here you can find the table.

The Web API Model “Books.cs” (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BooksApp.Models
{
    public class Books
    {
        public string BookName { get; set; }
    }
}

Model “Books.vb” (Vb.Net)

Imports System.Web

Namespace BooksApp.Models
    Public Class Books

        Public Property BookName() As String
            Get
                Return m_BookName
            End Get
            Set(value As String)
                m_BookName = Value
            End Set
        End Property
        Private m_BookName As String
    End Class
End Namespace

The Web API Controller BooksController.cs (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.http;
using System.Web.http;

using BooksApp.Models;
using System.Data.SqlClient;

namespace BooksApp.Controllers
{
    public class BooksController : ApiController
    {
        // LIST OBJECT WILL HOLD AND RETURN A LIST OF BOOKS.
        List<Books> MyBooks = new List<Books>();

        // RETURN A LIST OF BOOKS MATCHING WITH THE REQUESTED ALPHANUMERIC VALUE(S).
        public IEnumerable<Books> Get(string sLookUpString)
        {
            GetTheBooks(sLookUpString);
            return MyBooks;
        }

        public void GetTheBooks(string sFind)
        {
            string sConnString = "Data Source=DNA;Persist Security Info=False;" +
                "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=demo;Connect Timeout=30;";

            SqlConnection myConn = new SqlConnection(sConnString);

            // SEARCH DATABASE TABLE MATCHING BOOKS WITH THE "LOOKUP" STRING.
            SqlCommand objComm = new SqlCommand("SELECT *FROM dbo.Books " +
                "WHERE BookName LIKE '%'+@LookUP+'%' ORDER BY BookName", myConn);
            myConn.Open();

            objComm.Parameters.AddWithValue("@LookUP", sFind);
            SqlDataReader reader = objComm.ExecuteReader();

            // ADD EACH BOOKNAME IN THE LIST.
            while (reader.Read())
            {
                MyBooks.Add(new Books { BookName = reader["BookName"].ToString() });
            }
            myConn.Close();
        }
    }
}

BooksController.vb (Vb.net)

Option Explicit On

Imports System.Net.http
Imports System.Web.http

Imports System.Data.SqlClient
Imports BooksApp.BooksApp.Models

Namespace BooksApp
    Public Class BooksController
        Inherits ApiController

        ' LIST OBJECT WILL HOLD AND RETURN A LIST OF BOOKS.
        Dim MyBooks As New List(Of Books)()

        ' RETURN A LIST OF BOOKS MATCHING WITH THE REQUESTED ALPHANUMERIC VALUE(S).
        Public Function [Get](sLookUpString As String) As IEnumerable(Of Books)
            GetTheBooks(sLookUpString)
            Return MyBooks
        End Function

        Public Sub GetTheBooks(sFind As String)

            Dim sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _
                "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=demo;Connect Timeout=30;"

            Dim myConn As New SqlConnection(sConnString)

            ' SEARCH DATABASE TABLE MATCHING BOOKS WITH THE "LOOKUP" STRING.
            Dim objComm As New SqlCommand("SELECT *FROM dbo.Books " & _
                "WHERE BookName LIKE '%'+@LookUP+'%' ORDER BY BookName", myConn)

            myConn.Open()

            objComm.Parameters.AddWithValue("@LookUP", sFind)
            Dim reader As SqlDataReader = objComm.ExecuteReader()

            ' ADD EACH BOOKNAME IN THE LIST.
            While reader.Read()
                MyBooks.Add(New Books() With { _
                    .BookName = reader("BookName").ToString() _
                 })
            End While

            myConn.Close()
        End Sub

    End Class
End Namespace

Once we have created our API along with the SQL Server table, we now need an HTML page that will have the textbox and jQuery script with Ajax and TypeAhead methods.

The Markup of default.htm
<!DOCTYPE html>
<html>
<head>
    <title>Twitter Bootstrap TypeAhead Ajax Example</title>

    <link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css' media="screen" />
    <link rel="Stylesheet" href="https://twitter.github.io/typeahead.js/css/examples.css" />
    <script src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
    <script src="https://cdn.rawgit.com/bassjobsen/Bootstrap-3-Typeahead/master/bootstrap3-typeahead.min.js"></script>
</head>
<body>
    <div>
        <input type="text" id="myBooks" placeholder="Search Your Book" />
    </div>
</body>
The jQuery Script
<script>
    $(document).ready(function () {
        BindControls();
    });

    function BindControls() {
        $('#myBooks').typeahead({
            source: function (request, response) {
                $.ajax({
                    url: "/api/books/" + request,
                    dataType: "json",
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        var arrBooks = [];
                        response($.map(data, function (item) {
                            arrBooks.push(item.BookName);
                        }))
                        response(arrBooks);

                        // SET THE WIDTH AND HEIGHT OF UI AS "auto" ALONG WITH FONT.
                        // YOU CAN CUSTOMIZE ITS PROPERTIES.
                        $(".dropdown-menu").css("width", "auto");
                        $(".dropdown-menu").css("height", "auto");
                        $(".dropdown-menu").css("font", "15px Verdana");
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            hint: true,             // SHOW HINT (DEFAULT IS "true").
            highlight: true,        // HIGHLIGHT (SET <strong> or <b> BOLD). DEFAULT IS "true".
            minLength: 1            // MINIMUM 1 CHARACTER TO START WITH.
        });
    }
</script>
</html>

The source: property of the typeahead() method has the Ajax function that will take the input as request and calls the API Controller. The Controller (I have defined above) receives the request input, fetches data in the database for a matched list and returns the list. The list (a JSON) in the Ajax is stored in an array arrBooks.

The typeahead’s UI component, which is an HTML unordered list (<ul>) with class .dropdown-menu receives the list and it displays the data just below the textbox control. As you can see, I have set the width, height and font of the component according to my requirement. You can custom set the properties.

You can learn more about the properties, methods and options here.

Hope you will find this example interesting and useful. You can now add Twitter AutoComplete feature in your application too. Its a fast and tested jQuery plug-in as it is used extensively by Twitter. This plug-in works with static or hardcoded data at the client side along dynamic data, fetched from a remote database, as example that we saw here.

Let me know your opinion about this articles and its example.

← PreviousNext →