【问题标题】:jqGrid - Toolbar search with auto complete from server - using jsonjqGrid - 从服务器自动完成的工具栏搜索 - 使用 json
【发布时间】:2012-01-20 03:18:34
【问题描述】:

在查看这 2 个问题和 Oleg 的精彩答案后

can jqgrid support dropdowns in the toolbar filter fields

jqGrid toolbar search with autocomplete using json data

我正在尝试使用来自服务器的 json 数据自动完成 jQgrid 工具栏搜索来实现此功能。

我的代码:

    myGrid.jqGrid({
    url: './WebService.asmx/ViewNQueryData',
    datatype: 'json',
    mtype: 'POST',
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
    serializeGridData: function (postData) {
        if (postData.filters === undefined) postData.filters = null;
        return JSON.stringify(postData);
    },
    jsonReader: {
        root: function (obj) { return obj.d.rows; },
        page: function (obj) { return obj.d.page; },
        total: function (obj) { return obj.d.total; },
        records: function (obj) { return obj.d.records; }
    },
    colModel: columnModel,
    colNames: columnNames,
    rowNum: 10,
    rowList: [10, 20, 300],
    sortname: 'ID',
    sortorder: "asc",
    sortable: true,
    pager: "#ViewNQueryPager",
    viewrecords: true,
    gridview: true,
    height: 250,
    shrinkToFit: true,//If using frozen coulmns change to false.
    grouping: true,
    groupingView: {
        groupField: ['ID'],
        //groupColumnShow: [false],
        //groupText: ['<b>{0} - {1} Item(s)</b>'],
        groupSummary: [true],
        groupOrder: ['asc'],
        groupDataSorted: true,
        showSummaryOnHide: true
    },
    footerrow: true,
    userDataOnFooter: true,
    gridComplete: function () {
        $('#totalRecordsFound').html(myGrid.jqGrid('getGridParam', 'records') + " Customers");
    },
    loadError: function () {
        alert("Error fetching data");
    }
}).jqGrid('navGrid', '#ViewNQueryPager',
                { edit: false, add: false, del: false, search: true, view: true }, //option
                {}, // use default settings for edit
                {}, // use default settings for add
                {}, // delete instead that del:false we need this
                {multipleSearch: true, multipleGroup: true, showQuery: true, onSearch: function (response) { showQueryDetails(); } },
                { height: 250, jqModal: false, closeOnEscape: true} // view options
                );

myGrid.jqGrid('setColProp', 'FirstName',
        {
            searchoptions: {
                sopt: ['cn'],
                dataInit: function (elem) {
                    $(elem).autocomplete({
                        source: './WebService.asmx/ViewNQueryData',
                        minLength: 1
                    });
                }
            }
        });

myGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true });

但是当我在搜索框中输入请求时,我的 webService 并没有收到,而且我在浏览器中遇到异常,他正在尝试这样做:

http://localhost:50949/WebService.asmx/ViewNQueryData?term=p

但是:
加载资源失败:服务器响应状态为 500 (Internal Server Error)

我的网络服务:

public JqGridData ViewNQueryData(int page, int rows, string sidx, string sord, bool _search, string filters)
{

    if (_search && !String.IsNullOrEmpty(filters))
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        jqGridSearchFilter searchFilter =
            serializer.Deserialize<jqGridSearchFilter>(filters);
        // use the searchFilter here
    }
    List<Person> allGridRows = JsonHelper.GetPersons();
    int recordsCount = allGridRows.Count;

    int startIndex = (page - 1) * rows;
    int endIndex = (startIndex + rows < recordsCount) ?
                   startIndex + rows : recordsCount;

    List<TableRow> gridRowsForResponse = new List<TableRow>(rows);
    for (int i = startIndex; i < endIndex; i++)
    {
        gridRowsForResponse.Add(new TableRow()
        {
            id = i,
            cell = new List<string>(3) {
                allGridRows[i].ID.ToString(),
                allGridRows[i].FirstName,
                allGridRows[i].LastName
        }
        });
    }

    return new JqGridData()
    {
        total = (recordsCount + rows - 1) / rows,
        page = page,
        records = recordsCount,
        rows = gridRowsForResponse
    };
}

我做错了什么?遗漏了什么? 另外我需要从服务器返回什么?网格需要的常规 JSON?

【问题讨论】:

    标签: search jqgrid autocomplete jqgrid-asp.net


    【解决方案1】:

    错误是您对 jQuery UI 自动完成和主网格 url 使用相同的 URL './WebService.asmx/ViewNQueryData'

    主网格url 应该调用带有(int page, int rows, string sidx, string sord, bool _search, string filters) 参数的web 方法并以格式返回JSON 数据

    {
        "d": {
            "__type": "JqGridData",
            "total": 3,
            "page": 1,
            "records": 24,
            "rows": [
                {"id": 10, "cell": ["1", "Prabir", "Shrestha"]},
                {"id": 20, "cell": ["2", "Scott", "Gu"]},
                {"id": 43, "cell": ["4", "Bill", "Gates"]}
            ]
        }
    }
    

    另一方面,jQuery UI 自动完成的 web 方法应该只有一个输入参数 term 并以如下格式返回数据

    ["Bill", "Scott"]
    

    [
        {
            "label": "Crab-Plover",
            "value": "Crab-Plover"
        },
        {
            "id": "Oenanthe isabellina",
            "label": "Isabelline Wheatear",
            "value": "Isabelline Wheatear"
        }
    ]
    

    请参阅 jQuery UI 自动完成 documentation 的“数据模型”部分。

    因为您使用将返回的 JSON 数据包装在 d 属性 ({d:{...}}) 中的 ASMX Web 服务,所以您必须使用一些额外的修改来以一种受支持的格式为 jQuery UI 自动完成提供数据。例如,您可以在回调形式中使用 Autocomplete 的 source 参数,而不是简单的 URL 字符串。例如,请参阅 the answer(或 this one)。

    【讨论】:

      猜你喜欢
      • 2011-08-27
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 2015-03-31
      相关资源
      最近更新 更多