Grid中的Kendo DropDownList在选择后显示值

时间:2014-02-14 17:16:52

标签: javascript kendo-ui kendo-grid kendo-dropdown

我正在尝试在网格中使用下拉列表。这是我的网格定义:

$("#grid").kendoGrid({
    editable: true,
    dataSource: {
        data: data,
        schema: {
            model: {
                fields: {
                    Name: {
                        type: "string",
                        editable: false
                    },
                    FruitName: {
                        type: "string"
                    },
                    FruitID: {
                        type: "number"
                    }
                }
            }
        }
    },
    columns: [{
        field: "Name",
        title: "Name",
        width: 150
    }, {
        field: "Fruit",
        title: "Fruit",
        width: 115,
        editor: renderDropDown,
        template: "#=FruitName#"
    }]
});

这是我的编辑功能:

function renderDropDown(container, options) {
    var dataSource = [
    //{ name: "", id: null },
    {
        FruitName: "Apple",
        FruitID: 1
    }, {
        FruitName: "Orange",
        FruitID: 2
    }, {
        FruitName: "Peaches",
        FruitID: 3
    }, {
        FruitName: "Pears",
        FruitID: 4
    }];

    $('<input required  name="' + options.field + '"/>')
        .appendTo(container)
        .kendoDropDownList({
        dataTextField: "FruitName",
        dataValueField: "FruitID",
        dataSource: dataSource
    });
}

这是一个关于JSBin的演示,用于说明:http://jsbin.com/malev/3/edit

我的问题是两部分。

  1. 为什么此示例中的下拉列表在编辑之前不会默认为列中的值?

  2. 为什么文本在选择后切换到值?

1 个答案:

答案 0 :(得分:7)

查看您的列定义:

{
    field: "Fruit",
    title: "Fruit",
    width: 115,
    editor: renderDropDown,
    template: "#=FruitName#"
}

您的字段名称为Fruit。在编辑器中,您绑定到此字段名称,但您的架构模型和数据仅具有FruitID属性。这解释了为什么下拉列表没有正确显示初始值。

另一个问题是,如果您需要从编辑器更新模型上的两个属性,则需要手动执行此操作,例如:通过这样设置您的编辑器:

$('<input required  name="' + options.field + '"/>')
    .appendTo(container)
    .kendoDropDownList({
    dataTextField: "FruitName",
    dataValueField: "FruitID",
    dataSource: dataSource,
    change: function (e) {
        var dataItem = e.sender.dataItem();
        options.model.set("FruitName", dataItem.FruitName);
    }
});

另一种方法是使用查找函数为您提供给定值的显示文本,例如:

var fruitNames = ["", "Apple", "Orange", "Peaches", "Pears"];
function getFruitName(value) {
    return fruitNames[value];
}

然后你可以在模板中使用它:

template: "#= getFruitName(FruitID) #"

并且您不需要在编辑器中为名称和更改处理程序添加单独的列。

updated demo