ASP.NET MVC

AutoComplete Textbox Using Typeahead JS In ASP.NET MVC

Here, in this post, we will discuss the Typeahead JS plugin which is used for Autocomplete textbox. It is something better than jQuery UI which is also used for autocomplete textbox but the problem with jQuery UI is that we have to manage the sequence as two files are there for it. While in Typeahead only one file is used so no headache for managing sequence.

We have to include the following CDN for Typeahead

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  

We are going to use the code first approach for it. If you are not familiar with it than you can see the article on Code First Approach

Now I assume that you know about Code first Approach so we directly dive towards integrating Typeahead.

So first we start with the _Layout file. Include the typeahead js reference in it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    <script src="~/Scripts/bootstrap3-typeahead.min.js"></script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @RenderSection("scripts", required: false)
</body>
</html>

Now navigate to View -> Home -> Index.cshtml

@{
    ViewBag.Title = "Home Page";
}
<br />
<div class="row">
    <div class="form-group col-md-5">
        <input type="text" id="select" class="form-control" />
    </div>
    <div class="form-group col-md-5">
        <input type="text" id="update" disabled class="form-control" />
    </div>
</div>
<script>
    $("#select").typeahead({
        minLength: 1,
        source: function (request, response) {
            $.ajax({
                url: "/Home/GetList/",
                data: { "name": request },
                type: "GET",
                contentType: "json",
                success: function (data) {
                    items = [];
                    map = {};
                    $.each(data, function (i, item) {
                        var id = item.Name;
                        var name = item.Name;
                        map[name] = { id: id, name: name };
                        items.push(name);
                    });
                    response(items);
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            });
        },
        updater: function (item) {
            //If simultaneously want to update value somewhere else
            $("#update").val(map[item].id);
            return item;
        }
    });
</script>

We are going to use TypeAheads table.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TypeaheadJSDemo.Models;

namespace TypeaheadJSDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly Context _context = new Context();
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetList(string name)
        {
            var list = _context.TypeAheads.Where(x => x.Name.StartsWith(name)).Take(10).ToList();
            return Json(list, JsonRequestBehavior.AllowGet);
        }
    }
}

We will only take the first 10 matching data rather than all data.

Output:

You can download the source code form here

 

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

View Comments

  • Thank you for the excellent example. I'm new to ASP.Net. I'm using ASP.NET Core and I'm trying to add client-side libraries. I find many typeahead libraries of which bootstrap-3-typeahead@4.0.2 is one. The description says it's for Bootstrap 2 but ready for Bootstrap 3. Given that I'm using Bootstrap 4.5 will this cause any problems? I can't seem to find Bootstrap 4.5 specific libraries or scripts for Typeahead. Should one be using something else for Bootstrap 4.5?

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago