0

数据源定义为:

var KendoDataSource_EmployeeAutoCompleteByFirstName = {
    serverFiltering: true,
    serverPaging: true,
    serverSorting: true,
    pageSize: 10,
    transport: {
        read: {
            url: '@Url.Action("GetEmployeesByFirstName", "Employee")',
            dataType: "json"
        }
    }
};

自动完成定义为:

function KendoGridFilterAutoComplete(element, kendoDataSource, textField) {
    element.kendoAutoComplete({
        minLength: 3,
        filter: "startswith",
        dataSource: kendoDataSource,
        dataTextField: textField
    });
}

使用 kendoAutoComplete 小部件时,数据源发送的过滤器如下:

filter[logic]=and&
filter[filters][0][value]=smith&
filter[filters][0][operator]=startswith&
filter[filters][0][field]=LastName&
filter[filters][0][ignoreCase]=true

来自服务器的 JSON 响应如下所示:

[
    {"First":"Bill","LastName":"Smith"},
    {"First":"Jack","LastName":"Smith"},
    {"First":"ABC","LastName":"Smithy"}
]

这很好用,但是正如您所见,我返回了多个条目,因此 kendoAutoComplete 显示了两个相同的条目(Smith),因为名字不同。

所以我真正想要的是在服务器上做不同的事情,并且只返回可能的姓氏,作为一个字符串数组,如下所示:

[
    "Smith",
    "Smithy"
]

然而 kendoAutoComplete 不能处理这个。它显示“未定义”或错误。

如何解决这个问题?

4

1 回答 1

0

我创建了以下代码:

#region AutoComplete
public virtual IQueryable GetAutoComplete(KendoGridRequest request)
{
    // Get filter from KendoGridRequest (in case of kendoAutoComplete there is only 1 filter)
    var filter = request.FilterObjectWrapper.FilterObjects.First();

    // Change the field-name in the filter from ViewModel to Entity
    string fieldOriginal = filter.Field1;
    filter.Field1 = MapFieldfromViewModeltoEntity(filter.Field1);

    // Query the database with the filter
    var query = Service.AsQueryable().Where(filter.GetExpression1<TEntity>());

    // Apply paging if needed
    if (request.PageSize != null)
    {
        query = query.Take(request.PageSize.Value);
    }

    // Do a linq dynamic query GroupBy to get only unique results
    var groupingQuery = query.GroupBy(string.Format("it.{0}", filter.Field1), string.Format("new (it.{0} as Key)", filter.Field1));

    // Make sure to return new objects which are defined as { "FieldName" : "Value" }, { "FieldName" : "Value" } else the kendoAutoComplete will not display search results.
    return groupingQuery.Select(string.Format("new (Key as {0})", fieldOriginal));
}

public virtual JsonResult GetAutoCompleteAsJson(KendoGridRequest request)
{
    var results = GetAutoComplete(request);
    return Json(results, JsonRequestBehavior.AllowGet);
}
#endregion

它返回一个匿名对象的唯一列表,看起来像 { "LastName" : "a" }。

于 2013-11-18T13:27:08.047 回答