无法使用Twitter Bootstrap Typeahead发布ID

时间:2016-09-24 19:59:09

标签: javascript asp.net-mvc twitter-bootstrap bootstrap-typeahead twitter-typeahead

我在我的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);
}

1 个答案:

答案 0 :(得分:1)

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