Answer:
a working implementation:
<link rel="stylesheet" href="@Url.Content("//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css")">
<script src="@Url.Content("//code.jquery.com/jquery-1.10.2.js")"></script>
<script src="@Url.Content("//code.jquery.com/ui/1.11.4/jquery-ui.js")"></script>
<script type="text/javascript">
$(function () {
$("#ItemCode").autocomplete({
source: function (request, response) {
var itemnamecodes = new Array();
$.ajax({
async: false, cache: false,
//type: "POST",
url: "@(Url.Action("GetItemCode", "Home"))",
data: { "term": request.term },
success: function (data) {
for (var i = 0; i < data.length ; i++) {
itemnamecodes[i] = { label: data[i].Value, Id: data[i].Key };
}
}
});
response(itemnamecodes);
},
select: function (event, ui) {
$.ajax({
cache: false, async: false, type: "POST",
url: "@(Url.Action("GetItemDetails", "Home"))",
data: { "id": ui.item.Id },
success: function (data) {
var item = data[0];
$("#ItemName").val(item.ItemName);
$("#ItemModel").val(item.ItemModel);
... the other details you need
action = data.Action;
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve Item.');
}
});
}
});
});
</script>
@using (Html.BeginForm())
{
...
@Html.EditorFor(model => model.ItemCode, ...
@Html.EditorFor(model => model.ItemName, ...
... other form elements to show details
In Controller,
public JsonResult GetItemCode(string term)
{
// var codes = db.w_Items.Where(i => i.ItemCode.StartsWith(term)).ToList();
var result = new List<KeyValuePair<string, string>>();
var namecodes = new List<SelectListItem>();
namecodes = (from u in db.w_Items select new SelectListItem { Text = u.ItemCode, Value = u.w_ItemId.ToString() }).ToList();
foreach (var item in namecodes)
{
result.Add(new KeyValuePair<string, string>(item.Value.ToString(), item.Text));
}
var namecodes1 = result.Where(s => s.Value.ToLower().Contains
(term.ToLower())).Select(w => w).ToList();
return Json(namecodes1, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetItemDetails(int id)
{
var codeList = db.w_Items.Where(i => i.w_ItemId == id).ToList();
var viewmodel = codeList.Select(x => new
{
Id = x.w_ItemId,
ItemName = x.ItemName,
ItemModel = x.ItemModel,
... the other details you need
});
return Json(viewmodel);
}
Two things that were irking:
(Solutions here)
the json data is in the form of array, so you need to treat it likewise:
var item = data[0];
and another very irking thing.. solution now:
you need to pass viewmodel with specific properties as json result to be handled in View