我有一个Kendo Grid,在DataBound
事件中,我想将其数据源添加到Kendo MultiSelect中。因此,当加载来自网格的数据时,将触发以下函数。
这是我到目前为止所尝试的内容,没有成功,但是从代码中你可以看到我想要的内容:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource._data;
for (var i = 0; i < places.length; i++) {
var row = instPlaces[i];
var id = row.Id;
var mediumDescription = row.MediumDescription;
alert(id + " - " + mediumDescription);
multiSelect.dataSource.insert(i, { text: mediumDescription, value: id })
}
multiSelect.dataSource.read();
}
警报会正确显示所有数据网格项目的ID和描述,因此,我可以从网格中获取数据。
我将它们添加到multiSelect的数据源中,最后一行是刷新它并显示新数据,但它并没有。 multiSelect仍为空。
答案 0 :(得分:3)
尝试以下方法:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource.data();
// Read original data content
var multiData = multiSelect.dataSource.data();
for (var i = 0; i < places.length; i++) {
...
// insert new element into copy of multiselect data
multiData.push({ text: mediumDescription, value: id })
}
// Write back the modified data
multiSelect.dataSource.data(multiData);
}
请参阅以下代码示例:
$(document).ready(function() {
function addToMultiSelect(e) {
var grid = this;
var data = this.dataSource.data();
var multiData = [];
for (var i = 0; i < data.length; i++) {
multiData.push({ text: data[i].ShipName, value: i });
}
multi.dataSource.data(multiData);
}
var multi = $("#multi").kendoMultiSelect({
dataSource: {
data: [
{ text: "ship 1", value: 1 },
{ text: "ship 2", value: 2 },
{ text: "ship 3", value: 3 },
{ text: "ship 4", value: 4 }
]
},
dataTextField: "text",
dataValueField: "value"
}).data("kendoMultiSelect");
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: addToMultiSelect,
height: 550,
columns: [
"OrderID",
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShipCity",
title: "Ship City"
}
]
});
});
html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>
Ship Names copied from Grid DataSource: <input id="multi"/>
Grid
<div id="grid"></div>