【发布时间】:2018-05-31 06:41:13
【问题描述】:
我需要使用 ajax 实现 select2,并且我使用 this 作为示例项目。
这是我目前所拥有的
查看
<div class="form-group">
<div class="col-md-10">
<select class="js-data-example-ajax form-control"></select>
</div>
</div>
$(document).ready(function () {
$('.js-data-example-ajax').select2({
placeholder: 'Enter name',
//Does the user have to enter any data before sending the ajax request
minimumInputLength: 3,
allowClear: true,
ajax: {
quietMillis: 150,
// url: '@Url.Action("GetUsers", "CRMTItems")',
url: '/CRMTItems/GetUsers/' + $('.js-data-example-ajax').text(),
dataType: 'jsonp',
results: function (data) {
console.log('results');
return { results: data.results }
}
// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
}
});
)};
控制器
public JsonResult GetUsers(string term)
{
var users = CRMTItemViewModel.AllUsers.Where(u => u.DisplayName.Contains(term));
var userList = AttendeesToSelect2Format(users, 10);
return Json(userList, JsonRequestBehavior.AllowGet);
}
我可以看到传入了搜索词并过滤了数据,但是当它被发送回视图时我只看到了
我尝试完全复制示例项目,但后来遇到了更多问题:
-
当我使用
@Html.TextBoxFor而不是<select>时,我看到了没有 select2/compat/inputData
在 js 控制台中
-
当完全复制 js 时(使用
data和results函数),我的搜索词永远不会到达控制器,并且每次都会传入null..
请有人帮忙解决一下,我不明白
【问题讨论】:
-
jsonp->json -
同时检查控制台网络选项卡,您正在从服务器接收数据?
-
@Andreas 改成
json后我现在得到Cannot read property 'slice' of undefined -
检查响应是否符合 select2 预期的格式
-
@Andreas 它看起来像这样
{"Total":10,"Results":[{"id":"_spocrawler_24_3595","text":"_spocrawler_24_3595"},{"id":"_spocrwl_319_15489","text":"_spocrwl_319_15489"},{"id":"sp_farm_svc_sponline@domain.com","text":"sp_farm_svc_sponline"},{"id":"_spocrwl_19649","text":"_spocrwl_19649"}]},我认为这是对的?
标签: javascript c# asp.net-mvc jquery-select2