1
我想在我的MVC項目自動完成多個值,但它自動完成對第一個值和第二沒有發生
我的視圖代碼:
MVC jQuery的自動完成多個值首次工作只
@Html.TextBox("SentUsers", "", new { @class = "text-box"})
@Html.Hidden("UsersId")
Java腳本代碼:
<script type="text/javascript">
var customData = null;
var userId;
$(function() {
$("#SentUsers")
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: "/Ajax/AutoCompleteUsers",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
alert(data);
customData = $.map(data, function (item) {
userId = item.UserId;
return { label: item.Name + "(" + item.Email + ")", value: item.Name }
});
response(customData, extractLast(request.term))
}
})
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var usersIdVal = $("#UsersId").val();
usersIdVal += ", " + userId;
$("#UsersId").val(usersIdVal)
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
控制器代碼:
public JsonResult AutoCompleteUsers(string term)
{
var result = (from r in db.UserItems
where r.Name.ToLower().Contains(term.ToLower())
select new { r.Name, r.Email, r.UserId }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
!
我認爲錯誤可能是在這一塊,但我不知道該解決方案
customData = $.map(data, function (item) {
userId = item.UserId;
return { label: item.Name + "(" + item.Email + ")", value: item.Name }
});