在Kendo Grid中创建动态列(Javascript)

时间:2013-02-25 13:07:34

标签: kendo-grid

我想用动态列创建一个kendo网格,所有列都将在客户端创建。

作为一个例子:

我编写了以下代码来创建网格:

var grid = $("#grid");
        grid.children().remove();
        grid.kendoGrid({
            columns: [{ title: 'One', width: '100px' }, { title: 'Two', width: '100px' }, {title: 'Three', width:'100px'}],
            dataSource: {
                transport: {
                    read: {
                        url: "@Url.Action("")",
                        type: "GET",
                        dataType: "json",
                        traditional: true,
                        data: {
                            itemTypeId: $("#").val(),
                            where: ["", "", "", "", ""],
                            orderBy: ["", "", ""],
                        },
                    },
                },
                schema: {
                    data: "",
                    total: "",
                },
                serverPaging: true,
                pageSize: 4,
                error: function (e) {
                    alert(e.errors);
                }
            },
            pageable: true,
            resizable: true,
            reorderable: true,
        })
    }

当我通过以下方式定义列时:

columns: [{ title: 'One', width: '100px' }, { title: 'Two', width: '100px' }, {title: 'Three', width:'100px'}],

上面的代码工作正常。

但是我想在一个无效的循环中创建所有这些列。

像: 我在javascript变量中保存模式,然后将其分配给kendo网格。

Var columnSchema = "{ title: 'One', width: '100px' },{ title: 'Two', width: '100px' },{ title: 'Two', width: '100px' }";

columns : [columnSchema]

但它不起作用。

1 个答案:

答案 0 :(得分:3)

对您的代码稍作修改,它应该有效:

var columnSchema = [{ title: 'One', width: '100px' },{ title: 'Two', width: '100px' },{ title: 'Three', width: '100px' }];

grid.kendoGrid({
    // .. other properties ..
    columns : columnSchema
});

您需要将columnSchema变量定义为数组而不是字符串(如我的示例所示),它将起作用。

您也可以构建数组,例如

var columnSchema = [];
columnSchema.push({ title: 'One', width: '100px' });
columnSchema.push({ title: 'Two', width: '100px' });
columnSchema.push({ title: 'Three', width: '100px' });

您可以在循环中使用push(..),如果需要,可以从其他位置读取列信息。

只要在使用变量初始化网格之前完成此操作即可。创建网格后,您无法更改列。

如果您需要在创建网格后更改列,则需要先调用destroy()方法,然后再使用新的列规范调用kendoGrid(..)

相关问题