Learn ASP.NET MVC, ASP.NET Core, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Utilize HTML5 DataList and jQuery Ajax to Create Autocomplete in ASP.NET MVC

In data entry forms involving textboxes with predictable values one can use autocomplete to assist user pick an existing value. HTML5 introduces <datalist> element that can come handy while implementing autocomplete. The <datalist> element holds a list of options and can be attached with a textbox using list attribute. By adding a bit of jQuery Ajax you can dynamically populate the options in a <datalist>. This article shows you how to do just that.

HTML5 <datalist> element is used as shown in the following markup.

<input type="text" list="datalist1" />

<datalist id="datalist1">
  <option value="US" label="United States" />
  <option value="UK" label="United Kingdom" />
  <option value="IN" label="India" />
</datalist>

At runtime the above markup shows an autocomplete as shown below:

Once you select an option from the list, the textbox is filled with the value. The <datalist> and its <option> elements are statically placed in the above markup. If you wish to dynamically populate the <datalist> based on the value entered in the textbox, you need to make an Ajax call to the server and fetch the required data.

Consider the following HTML markup that has a textbox and an empty <datalist>.

<h1>Autocomplete Example</h1>
<input id="companyName" list="companyList" />
<datalist id="companyList"></datalist>

To dynamically populate the <datalist> you can add the following jQuery code:

$(document).ready(function () {
    $("#companyName").on("input", function () {
        var options = {};
        options.url = "/home/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 + "'></option>");
            }
        };
        $.ajax(options);
    });

});

The above jQuery code wires the input event handler for the companyName textbox. The code makes an Ajax call to an MVC action method - GetCompanyList(). This action method returns a list of CompanyName values from Customers table of the Northwind database. While making the Ajax call you pass the textbox value to the action method as the search criteria. The success function receives an array of JavaScript objects. Each object has a single property - CompanyName - that is then filled in <option> elements of companyList.

The GetCompanyList() action method finds all the company names containing the entered text. The GetCompanyList() action is shown below:

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

Notice that GetCompanyList() action returns JsonResult using Json() method. Also notice that JsonRequestBehavior is set to AllowGet so that GET requests can call this method.

That's it! You can now run the application and test whether it dynamically displays the autocomplete. The following figure shows a sample run.

 

 




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 15 Dec 2014



Tags : ASP.NET AJAX MVC jQuery JavaScript