Twitter Typeahead在结果上返回完整对象

时间:2016-12-15 14:48:45

标签: javascript model-view-controller twitter autocomplete typeahead

我遇到了twitter typeaheadC# MVC的问题,当它自动完成时,会将整个对象打印到我的输入中:

image

我的代码:

var states = [];

@foreach (var item in ViewBag.Clubes)
{
    @:states.push({ "Nome" : "@item.Nome", "Id" : "@item.Id" })
}


$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1,
    valueKey: 'Nome',
    displayKey: 'Nome'
},
{
    name: 'value',
    source: substringMatcher(states),
    templates: {

    empty: [
      '<div class="empty-message">',
        ' Clube não encontrado ',
      '</div>'
    ].join('\n'),
    suggestion: function (data) {
        return "<strong>" + data.Nome + " " + data.Id + "</strong>";
    }

}
});

下拉建议中的值工作正常,但是当我选择它们时,他用数组对象填充输入,任何人都知道如何解决它?

感谢。

1 个答案:

答案 0 :(得分:1)

只需将值设置为您的先行输入框,如下所示

$('.typeahead').typeahead('val',data.Nome);

这是您的最终代码

var states = [];

@foreach (var item in ViewBag.Clubes)
{
    @:states.push({ "Nome" : "@item.Nome", "Id" : "@item.Id" })
}


$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1,
    valueKey: 'Nome',
    displayKey: 'Nome'
},
{
    name: 'value',
    source: substringMatcher(states),
    templates: {

    empty: [
      '<div class="empty-message">',
        ' Clube não encontrado ',
      '</div>'
    ].join('\n'),
    suggestion: function (data) {
        return "<strong>" + data.Nome + " " + data.Id + "</strong>";
    }

}
}).on('typeahead:selected', function(e, data) {
        $('.typeahead').typeahead('val',data.Nome);
});