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 asp.net 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 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();
}
[HttpPost]
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.
@modelMymvcApp.Models.Customer
@{
ViewBag.Title = "ajax autocomplete from database";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ContactName").autocomplete({
source: function (request, response){
$.ajax({
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 };
}))
}
})
}
});
})
</script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal" style="border: 1px solid #DED8D8; width: 450px; height: 305px;padding-left:15px;">
<h2>Autocomplete with keyValuePair in asp.net mvc</h2>
<div class="form-group">
<div class="col-md-12">
@Html.EditorFor(model => model.ContactName, new { htmlAttributes = new { @class = "form-control" }})
</div>
</div>
</div>
}
JQuery autocomplete search example: