jquery - 在 ASP.net MVC 中使用 Twitter Typeahead

标签 jquery asp.net-mvc twitter-bootstrap-3 typeahead.js twitter-typeahead

花了几个小时让 Twitter 预先输入显示自动完成值后,我很难弄清楚如何替换 Controller 中“创建”和“编辑”操作中的所有下拉列表。

我知道有几个问题。第一个是如何将所选对象的 ID(键)传递给 typeahead。我的 JSON 具有键值(基本上是 ID)和值值(即对象的名称)。 JSON 如下所示。

[{"Key":1,"Value":"Test1"},{"Key":2,"Value":"Test2)"},{"Key":4,"Value":"Adagreb d.o.o."},{"Key":5,"Value":"AGB Nielsen."}]

获取 JSON 并将其转换为 Javascript 对象数组后,数据将传递到应显示自动完成(提前输入)的控件。

        var substringMatcher = function (strs) {
        //ommited for brevity
        };

        function getJson(url) {
        //ommited for brevity
        }

        function simpleArray(target) {
            var arr = [];
            $.each(target, function (i, e) {
                $.each(e, function (key, val) {
                    arr.push(val);
                    console.log(val + "-" + key);
                });
            });
            return arr;
        }

        function typeaheadSetup(control, data) {          
            $(control).typeahead({
                hint: true,
                highlight: true,
                minLength: 2
            }, {
                displayKey: 'value',
                source: substringMatcher(simpleArray(data))
            });
        }

        var companies = getJson('/Ticket/GetCompanies');
        typeaheadSetup('#idFirma', companies);

我的问题是如何在显示值(Value)的同时传递 ID(Key),并且还能够通过将模型传递到数据库来保存它。

最佳答案

我们应该使用来自 typeahead 包的 BloodhoundttAdapter 可以从 typeahead:selected 事件中捕获选定的建议项。

以下是供您引用的脚本:

TestCase#1 与本地数据集 Working fiddle

<label for="company_search">Company Search:</label>
<input id="company_search" type="text" class="typeahead" />
<div id="selectedCompany"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/0.10.4/typeahead.bundle.js"></script>
<script>
   $(function () {
       var $SelectedCompany = $('#selectedCompany').hide(),
           companyList = [{"Key":1,"Value":"Test1"},{"Key":2,"Value":"Test2)"},{"Key":4,"Value":"Adagreb d.o.o."},{"Key":5,"Value":"AGB Nielsen."}];

       var companies = new Bloodhound({
           datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
           queryTokenizer: Bloodhound.tokenizers.whitespace,
           local: companyList
           //,prefetch: '/path/to/prefetch'
           //,remote: {/* You can use this for ajax call*/ } 
       });

       companies.initialize();

       $('#company_search').typeahead({ highlight: true, minLength: 2 }, {
           name: 'companies', displayKey: 'Value', source: companies.ttAdapter()
       })
       .on("typeahead:selected", function (obj, company) {
           $SelectedCompany.html("Selected Company: " + JSON.stringify(company)).show();
       });

   });
</script>

编辑:
TestCase#2 与远程数据集 Working fiddle

<input class="typeahead" placeholder="Type here to Search Movie..."></input>
<div id="selectedSuggestion"></div>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://twitter.github.io/typeahead.js/releases/0.10.4/typeahead.bundle.js"></script>
    <script>
   $(function () {
       //Docs: https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#remote
       var $SelectedSuggestion = $('#selectedSuggestion').hide(),
           movies = new Bloodhound({
               datumTokenizer: function (datum) {
                   return Bloodhound.tokenizers.whitespace(datum.title);
               },
               queryTokenizer: Bloodhound.tokenizers.whitespace,
               remote: {
                   url: 'http://api.themoviedb.org/3/search/movie?query=%QUERY&api_key=470fd2ec8853e25d2f8d86f685d2270e',
                   filter: function (movies) {
                       return movies.results;
                   }
               }
           });

       // Initialize the Bloodhound suggestion engine
       movies.initialize();

       // Instantiate the Typeahead UI
       $('.typeahead').typeahead(null, {
           displayKey: 'title',
           source: movies.ttAdapter()
       })
           .on("typeahead:selected", function (obj, selectedItem) {
           $SelectedSuggestion.html("Selected Suggestion Item: " + JSON.stringify(selectedItem)).show();
       });
   });
    </script>

关于jquery - 在 ASP.net MVC 中使用 Twitter Typeahead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26642340/

相关文章:

css - 在 IE9 中选择隐藏在 bootstrap 3 输入组中的 "arrow"

javascript - 使用JS/Jquery解析远程Xml文件?

javascript - 使用 jquery setInterval 运行 x 次

jquery - 从 ajax 发布 MVC Razor 表单

css - 背景网址不在文本下方

HTML 页边距错误

javascript - 如何在 Ajax 中传递动态 html 行的数据?

javascript - 如何根据区域坐标显示一个div

javascript - 有效估计 : How long to learn .net/javascript

c# - MVC 验证 - 更新另一个字段?