twitter打字后自动完成asp.net mvc jquery ajax的搜索操作

我使用Twitter typeahead(使用Bloodhound引擎)实现了自动完成function,并且运行正常。 我的下一步是使用生成/获得的数据(在我的情况下’name’和’id’)进行搜索操作。 这就是我遇到困难的地方。关于如何将数据传递给控制器​​以进行搜索操作,我完全空白。 我没有使用表单,但我想使用搜索按钮单击或js函数OnclickSearchButton或可能有更好的方法?!

我的JS代码:

$(document).ready(function () { var viewModel = {}; //will store id and string to pass for the search operation //var urlRoot = '/Test/GetName'; //we get url to the controller and min. char to invoke search from the html helper JavaScriptParameter var urlRoot = urlToController; //var lengthMin = 1; var lengthMin = minCharNeededForSearch; var information = { url: urlRoot, prepare: function (query, settings) { settings.type = "POST", settings.url += '?prefix=' + query; return settings; } }; var names = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('navn'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: information, }); //options $('#search').typeahead({ hint: false, minLength: lengthMin, highlight: true, }, //dataset { name: 'navn', //The name of the dataset display: 'name', // For a given suggestion, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. source: names, //the backing data source for suggestions limit: 10 //this is bug fix-around in Bloodhound engine so that it displays more than 1 or 2 record in the autocomplete }).on("typeahead:selected", function (e, datum) { //console.log(datum); //not sure if I can write a function here $('.search').on("click", function () { $.ajax({ type: 'POST', url: '/Test/GetResponse', data: datum, contentType: "application/json; charset=utf-8", success: function (data) { console.log("click function working"); } }); }); }); }); 

我对应的HTML:

 

我的asp.net控制器的方法:

 [HttpPost] public JsonResult GetName(string prefix) { var names = (from n in context.checkboxstates where n.Navn.StartsWith(prefix) select new { name = n.Navn, Id = n.Id }).ToList(); return Json(names); } 

我们将非常感谢您的帮助。

我发布了自动完成列表中“选定”字符串的解决方案:

只要用户通过按Enter键或单击按钮从自动完成列表中选择一个选项,就会触发此function。 我正在使用ajax调用而不是提交表单。

  $('#searchBox').bind('typeahead:select', function (event, datum) { $('#searchBox').keypress(function (event, datum) { if (event.which == 13) { $('.searchButton').trigger('click'); } }); $('.searchButton').click(function () { //code to implement search function }); });