无法 post 使用 Twitter Bootstrap Typeahead

Cannot post Id with Twitter Bootstrap Typeahead

我在我的 MVC5 项目中使用 Twitter Bootstrap Typeahead,它正确地列出了相关记录。虽然我可以在更新程序部分检索所选记录的 Id 值,但我无法在表单提交时 post 它。我尝试了 Id 参数的许多不同组合,但没有任何意义。如何使用 Twitter Bootstrap Typeahead post 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);
}

将字段分隔为名称和 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>