我有以下代码(javascript):
$('#cbxConnections').select2({
minimumInputLength: 0,
multiple: false,
allowClear: true,
placeholder:{
text:"@Diccionario.Connections",
id:" @Diccionario.Connections"
},
ajax:{
url:'@Url.Action("GetActiveConnections","Admin")',
dataType: 'json',
type:'post',
data:function(params){
return {
q: params.term
};
},
processResults: function(data,page){
return {
results: data
};
}
},
escapeMarkup: function (markup) {
return markup;
},
templateResult: function(response){
return '<div>'+response.Name+'</div>';
},
templateSelection: function(response){
return response.Id;
},
id: function(connection){
console.log(connection);
}
});
对于服务器端,我使用的是ASP MVC 4。 使用ajax选择获取数据并渲染选项,但此选项不可选。 阅读其他帖子,他们使用id函数进行描述,但是这个函数显然是在使用2.4
的select2版本中消失了我跟随github上显示的文档中的ajax示例 &#34;加载远程数据&#34;
答案 0 :(得分:58)
如果您的ajax响应没有 id 和文字属性,则应修复客户端
这是版本4.0的要求(不知道为什么)
ajax: {
processResults: function (data, params) {
params.page = params.page || 1;
// you should map the id and text attributes on version 4.0
var select2Data = $.map(data.result.data, function (obj) {
obj.id = obj._id.$id;
obj.text = obj.name;
return obj;
});
return {
results: select2Data,
pagination: {
more: data.result.more
}
};
}
}