【问题标题】:The results could not be loaded when searching for users搜索用户时无法加载结果
【发布时间】: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);
}

我可以看到传入了搜索词并过滤了数据,但是当它被发送回视图时我只看到了

我尝试完全复制示例项目,但后来遇到了更多问题:

  1. 当我使用@Html.TextBoxFor 而不是&lt;select&gt; 时,我看到了

    没有 select2/compat/inputData

    在 js 控制台中

  2. 当完全复制 js 时(使用 dataresults 函数),我的搜索词永远不会到达控制器,并且每次都会传入 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


【解决方案1】:

正如 Andreas 在评论中所建议的那样,这是因为

Results !== results

但我需要将Select2PagedResult中的Results属性更改为results,而不是更改js。

我不确定jsonp,但将其更改为json 似乎没有任何区别,即使该类在代码中称为JsonpResult

【讨论】:

  • “即使类在代码中被称为 JsonpResultpublic JsonResult GetUsers - 要么你错了,要么代码错了。
  • @Andreas 实际上the sample codeJsonpResult,它继承自JsonResult
猜你喜欢
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2016-07-29
  • 2014-05-15
  • 2020-03-16
  • 1970-01-01
相关资源
最近更新 更多