我在我的 MVC5 项目中使用 Twitter Bootstrap Typeahead,它正确列出了相关记录。虽然我可以在更新程序部分检索所选记录的 Id 值,但我无法将其发布到表单提交上。我尝试了 Id 参数的许多不同组合,但没有任何意义。如何使用 Twitter Bootstrap Typeahead 发布 Id 参数?
查看:
@Html.HiddenFor(m => m.StudentId)
<input id="StudentId" name="StudentId" type="text" class="form-control tt-input"
autocomplete="off" spellcheck="false" dir="auto">
<script>
$("#StudentId").typeahead({
minLength: 1,
source: function (query, process) {
var lookups = [];
map = {};
// This is going to make an HTTP post request to the controller
return $.post('/Grade/StudentLookup?query=%QUERY', { query: query }, function (data) {
// Loop through and push to the array
$.each(data, function (i, lookup) {
map[lookup.Name] = lookup;
lookups.push(lookup.Name);
});
// Process the details
process(lookups);
});
},
updater: function (item) {
var selectedId = map[item].Id;
console.log("Selected : " + selectedId);
return item;
}
});
</script>
Controller :
public ActionResult StudentLookup(string query)
{
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name + " " + m.Surname
})
.Where(m => m.Name.StartsWith(query));
return Json(students, JsonRequestBehavior.AllowGet);
}
最佳答案
将字段分为名称和 ID,您甚至可以将 ID 字段隐藏或只读。
<input id="StudentName" type="text" class="form-control tt-input"
autocomplete="off" spellcheck="false" dir="auto">
<input id="StudentId" name="StudentId" type="text">
<script>
$("#StudentName").typeahead({
minLength: 1,
source: function (query, process) {
var lookups = [];
map = {};
// This is going to make an HTTP post request to the controller
return $.post('/Grade/StudentLookup?query=%QUERY', { query: query }, function (data) {
// Loop through and push to the array
$.each(data, function (i, lookup) {
map[lookup.Name] = lookup;
lookups.push(lookup.Name);
});
// Process the details
process(lookups);
});
},
updater: function (item) {
var selectedId = map[item].Id;
console.log("Selected : " + selectedId);
$("#StudentId").val(selectedId)
return item;
}
});
</script>
关于javascript - 无法使用 Twitter Bootstrap Typeahead 发布 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39680418/