c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
asp.net MVC

Datalist autocomplete from database in jQuery

| | CSharp , JQuery , MVC

In this article I will show you how to use datalist to create jQuery autocomplete multiple values from database. You should make an Ajax call to server method GetCompanyList() and fetch company name and city from the customer table and return as JavaScript object bind into datalist element with values and label.

Here I am using Northwind database. You can download it from following link.

Download Northwind Database

Open Microsoft sql management studio and right click on the database and attach it.

Step 1: Create an ado.net entity data model using table Customer and generate entity for that.

Step 2: Right click on the "Controllers" folder and add "Home" controller. Copy and paste the following code.

 

public ActionResult Index()

        {
            return View();
        }


        public JsonResult GetCompanyList(string criteria)
        {
            models db = new models();
            var query = (from c in db.Customers
                         where c.CompanyName.Contains(criteria)
                         orderby c.CompanyName ascending
                         select new { c.CompanyName, c.City }).Distinct();
            return Json(query.ToList(), JsonRequestBehavior.AllowGet);
        }

Step 3: Right click on the HomeControllers and create an index view. Copy and paste the following code.

 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#companyName").on("input", function () {
            var options = {};
            options.url = "/autocomplete/getcompanylist";
            options.type = "GET";
            options.data = { "criteria": $("#companyName").val() };
            options.dataType = "json";
            options.success = function (data) {
                $("#companyList").empty();
                for (var i = 0; i < data.length; i++) {
                    $("#companyList").append("<option value='" +
                    data[i].CompanyName + "' label=" + data[i].City + "></option>");
                }
            };
            $.ajax(options);
        });
 
    });
</script>
<div style="border: 1px solid #DED8D8; width: 450px; height: 300px;padding-left:15px; font-family: Arial;">
    <h1>Datalist autocomplete from database in jQuery</h1>
    <input id="companyName" list="companyList" />
    <datalist id="companyList"></datalist>
 
</div>

 

html5 autocomplete datalist from database in jQuery