My View
@Html.LabelFor(model => Model.CustomerName, new { @class = "control-label" })
@Html.TextBoxFor(model => Model.CustomerName, new { @class = "form-control" })
@Html.HiddenFor(model => Model.CustomerID)
@Html.Label("Contact Person", new { @class = "control-label" })
@Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { @class = "form-control", type = "text", id = "CustomerContactID" })
My Jquery Code
<link href="~/Areas/Sales/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Areas/Sales/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/Areas/Sales/Scripts/jquery-ui.1.10.4min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerName").autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("GetVisitCustomer", "VisitorsForm")',
datatype: "json",
data: {
Areas: 'Sales',
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
debugger;
return {
label: val.Name,
value: val.Name,
customerId: val.ID
}
}))
}
})
},
select: function (event, ui) {
$("#CustomerID").val(ui.item.customerId);
debugger;
}
});
});
var Customerid = $("CustomerID").val();
$('#CustomerName').blur(function () {
debugger;
$('#CustomerContactID').empty();
$.ajax(
'@Url.Action("GetContactPersobByCustomerId", "VisitorsForm", new { Area = "Sales" })', {
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
My Controller Code public JsonResult GetVisitCustomer(string Areas, string term = "")
{
var objCustomerlist = db.Customers.Where(c => c.IsDeleted == false)
.Where(c => c.DisplayName.ToUpper()
.Contains(term.ToUpper()))
.Select(c => new { Name = c.DisplayName, ID = c.CustomerID })
.Distinct().ToList();
return Json(objCustomerlist, JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}