【发布时间】:2016-09-24 19:59:08
【问题描述】:
我在我的 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>
控制器:
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);
}
【问题讨论】:
-
控制台错误说明了什么,您可以在更新程序函数中使用console.log映射和项目并在源函数中查找吗?我认为您的问题是
map不是全球性的。 -
我在 selectedIndexChange 上将 Id 参数设置为“selectedId”,但无法将其分配给 StudentId 模型值。所以,唯一的问题是这个,请你澄清一下如何将它分配给 Model.StudentId?
-
啊,我建议您使用隐藏字段/另一个字段并为其分配 ID,否则您会混淆用户为什么将数字放置在他期望名称的位置。
-
是的,我也尝试使用隐藏字段并尝试在更新部分通过 $('#StudentId').value = selectedId ; 设置此值。但是没有工作,并且发布的 StudentId 值为 0,而 console.log() 的 StudentId 值正确。请问有什么答案吗?
-
你可以试试我的回答中的 .val(selectedId)
标签: javascript asp.net-mvc twitter-bootstrap bootstrap-typeahead twitter-typeahead