You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KendoUI Grid新增行默认在顶部,如何设置为底部显示?

Fix: Kendo UI Grid Show Empty Add Row at Bottom on Initial Load

Let's break down why your current attempts weren't working and fix the issue step by step:

Key Issues in Your Current Code

  1. Incorrect empty row structure: The newRow you added in $(document).ready() uses field and Value keys, which don't match your schema's model (which expects FirstName and Id).
  2. Timing problem: Adding the row right after Grid initialization might conflict with the initial data binding process, leading to the row appearing at the top instead of honoring createAt: "bottom".
  3. No check for duplicate empty rows: Without a guard clause, you might end up adding multiple empty rows if the dataBound event fires multiple times.

Working Solution

Here's the adjusted code with explanations:

var data = $scope.userdetails;
var dataSource = new kendo.data.DataSource({
    transport: {
        read: function (e) { e.success(data); },
        update: function (e) { e.success(); },
        create: function (e) {
            var item = e.data;
            item.Id = data.length + 1;
            e.success(item);
        }
    },
    schema: {
        model: {
            id: "Id",
            fields: { 
                FirstName: { type: "string" },
                Id: { type: "number", defaultValue: 0 } // Add default for Id to avoid validation issues
            }
        }
    }
});

let grid = $("#grid").kendoGrid({
    dataSource: dataSource,
    scrollable: false,
    navigatable: true,
    editable: { 
        createAt: "bottom",
        mode: "inline" // Ensure inline editing matches your setup
    },
    dataBound: function (e) {
        var grid = e.sender;
        // Keep your existing delete button style cleanup
        grid.tbody.find(".k-grid-Delete").each(function (idx, element) {
            $(element).removeClass("k-button");
        });

        // Add empty row at bottom ONLY if no existing empty row exists
        var data = grid.dataSource.data();
        var hasEmptyRow = data.some(item => item.FirstName === "" && item.Id === 0);
        
        if (!hasEmptyRow) {
            // Create a valid empty row matching the schema
            var emptyRow = { FirstName: "", Id: 0 };
            // Add to dataSource - createAt: "bottom" ensures it's added to the end
            grid.dataSource.add(emptyRow);
            // Wait for Grid to render the new row before editing it
            setTimeout(() => {
                grid.editRow(grid.tbody.find("tr:last"));
            }, 0);
        }
    },
    columns: [
        { field: "FirstName", title: "First Name" },
        { command: [{ name: "Delete", text: "", click: $scope.delete, className: "far fa-trash-alt fa-fw" }], title: " ", width: "100px", attributes: { class: "k-grid-column-text-centre" } }
    ]
}).data("kendoGrid");

// Keep your existing Tab key logic for adding new rows
grid.tbody.on('keydown', function (e) {
    if (e.keyCode == 9) {
        if ($(e.target).closest('tr').is(':last-child')) {
            setTimeout(function () {
                var totalrows = grid.dataSource.total();
                var data = grid.dataSource.data();
                var lastItem = data[data.length - 1];
                if (typeof lastItem !== 'undefined') {
                    if (lastItem.FirstName.trim() == "") return;
                }
                grid.addRow();
            })
        }
    }
});

What Changed & Why

  1. Fixed empty row structure: The empty row now uses FirstName and Id (matching your schema's model) with Id: 0 (a temporary value that gets replaced when the row is saved).
  2. Moved empty row logic to dataBound: This ensures the row is added after the initial data load completes, so createAt: "bottom" is properly respected. The setTimeout ensures the Grid has finished rendering before we trigger edit mode.
  3. Added duplicate check: The hasEmptyRow guard prevents adding multiple empty rows if dataBound fires again (e.g., after deleting a row).
  4. Added default Id value: This avoids validation errors when adding the empty row, since your model uses Id as the primary key.

Why Your Previous Attempts Failed

  • Try1 (move row after addRow()): Kendo Grid manages row positions based on the dataSource order, so manual row manipulation conflicts with internal Grid logic and won't persist.
  • Try2 (dataSource.add() in document.ready): The row structure was invalid, and the timing meant the Grid hadn't fully initialized to apply the createAt: "bottom" setting.
  • Try3 (load event): The DataSource's load event fires when data is read, but you need to wait for the Grid to finish binding that data to the DOM — which is exactly what the dataBound event is designed for.

内容的提问来源于stack exchange,提问作者Debbie.S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:53:13