Autocomplete dropdown in MVC5?
Kindly see code below:
HTML
@Html.LabelFor(model => Model.CustomerName, new { @class = "control-label" }) @Html.TextBoxFor(model => Model.CustomerName, new { @class = "form-control"}) @Html.HiddenFor(model => Model.CustomerID)
JS
$(document).ready(function () { $("#CustomerName").autocomplete({ source: function (request, response) { $.ajax({ url: '@Url.Action("GetVisitCustomer", "Home")', datatype: "json", data: { Areas: 'Sales', term: request.term }, success: function (data) { response($.map(data, function (val, item) { return { label: val.Name, value: val.Name, customerId: val.ID } })) } }) }, select: function (event, ui) { $("#CustomerID").val(ui.item.customerId); } });});
CODE
public JsonResult GetVisitCustomer(string Areas, string term = "") { var objCustomerlist = db.Customers.Where(c => c.IsDeleted == false) .Where(c => c.CustomerName.ToUpper() .Contains(term.ToUpper())) .Select(c => new { Name = c.CustomerName, ID = c.CustomerID }) .Distinct().ToList(); return Json(objCustomerlist, JsonRequestBehavior.AllowGet); }
Sample screenshot