JQuery search box autocomplete with key value pair in mvc

JQuery search box autocomplete with key value pair in mvc, someone asked me to explain?

In this article I will show you how to create jQuery autocomplete multiple values from database and bind text box with key and value pair using mvc.

The key value pair helps to populates with customer Id along with Customer name, the combination of key and value into the textbox. If the user enters the text in the search textbox, jQuery Ajax method call to server method Index() and fetch customerId and CustomerName from the customer table and return as Json result of the request.  The $map() method applies a function to each item in an object and bind the jQuery autocomplete values and label.

Here I am using Northwind database. You can download it from the following link.
Download Northwind Database
Open Microsoft sql management studio and right click on the database and attach it.

Step 1:  Create an 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 Index(string Prefix)
            models context = new models();
            //Searching records from list using LINQ query 
            var cust = (from c in context.Customers
                          wherec.CustomerID.ToString().StartsWith(Prefix) || c.ContactName.ToLower().StartsWith(Prefix.ToLower())
                          select new { c.ContactName,c.CustomerID });
            return Json(cust, JsonRequestBehavior.AllowGet);


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

    ViewBag.Title = "ajax autocomplete from database";
<link rel="stylesheet" href="//">
<script src="//"></script>
<script src="//"></script>
<script type="text/javascript">
    $(document).ready(function () {
            source: function (request, response){
                    url: "/KeyValuePair/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix:request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label:item.CustomerID + "-" + item.ContactName, value: item.CustomerID };
@using (Html.BeginForm())
    <div class="form-horizontal" style="border: 1px solid #DED8D8; width: 450px; height: 305px;padding-left:15px;">
        <h2>Autocomplete with keyValuePair in mvc</h2>
        <div class="form-group">
            <div class="col-md-12">
                 @Html.EditorFor(model => model.ContactName, new { htmlAttributes = new { @class = "form-control" }})

JQuery autocomplete search example:

jquery autocomplete ajax multiple values

Post your comments / questions