Enable Kendo Grid Edit mode on Button Click(Custom Toolbar Button)

1 Answer 23 Views
Button Grid Toolbar
abdul
Top achievements
Rank 1
Iron
abdul asked on 10 Dec 2024, 06:01 PM

Hi,

I have a Kendo grid as below. On Click of a custom toolbar button(Edit) I want to enable all the rows of the grid.

1. When the user clicks on Edit button it should enable all the rows to edit mode.

2. The Edit button text should change to Update on click of Edit button.

3. Then user change the rows and select the checkbox, and click on the update button, then only the selected checked rows will send to server for update.

Please help me find the above requirements solutions.

 

1 Answer, 1 is accepted

Sort by
0
Mihaela
Telerik team
answered on 13 Dec 2024, 11:55 AM

Hello Abdul,

Indeed, you can achieve this scenario as follows:

1) Add a Button above the Grid and handle its Click event. Change the Button's label with jQuery based on its current label:

@(Html.Kendo().Button()
    .ThemeColor(ThemeColor.Success)
    .Name("editBtn")
    .Content("Edit")
    .HtmlAttributes(new { title = "Edit" })
    .Events(ev => ev.Click("onClickEdit"))
)

<script>
    function onClickEdit(e) {
        if ($("#editBtn .k-button-text").text() == "Edit") {
            $("#editBtn .k-button-text").text("Update");
        } else {
            $("#editBtn .k-button-text").text("Edit");
        }
    }
</script>

2) Configure the Grid for InCell editing and disable the default edit mode of each column through the .Editable("function() { return false}") configuration. Ensure that the unique Model identifier is specified in the DataSource configuration and do not set Update() option.

        @(Html.Kendo().Grid<GridViewModel>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.Select().Width(50);
                columns.Bound(p => p.TapeDate).Format("{0:MM/dd/yyyy}").Editable("function() { return false}");
                columns.Bound(p => p.TermPoint).Editable("function() { return false}");
                ...
                columns.Bound(p => p.TLP).Editable("function() { return false}");
            })
            .PersistSelection(true)
            .Editable(editable => editable.Mode(GridEditMode.InCell))
            .Pageable()
            .Scrollable()
            .Filterable()
            .HtmlAttributes(new { style = "height:550px;" })
            .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(10)
                .ServerOperation(false)
                .Model(m => m.Id("Id"))
                .Read(read => read.Action("Read", "Grid"))
            )
        )

3) Within the Click event of the "Edit" button, access the Grid columns, loop through them and set a "template" option for each column with the desired editor (i.e., a TextBox for the string fields, a NumericTextBox for the numeric fields, and so on). Subscribe to the DataBound event of the Grid and bind each data item to the respective input element. Then, update the Grid settings by calling the setOptions() method. As a result, the template of each column will be updated with the respective editor and all Grid rows will be rendered in edit mode.

    function onClickEdit(e) {
        var grid = $("#grid").data("kendoGrid");
        if ($("#editBtn .k-button-text").text() == "Edit") {
            $("#editBtn .k-button-text").text("Update");

            var currentColumns = grid.columns;
            $.each(currentColumns, function (idx, column) {
                if (column.field == "TapeDate") {
                    column.template = `<input data-role='datepicker' data-bind='value:TapeDate' class='k-input' />`;
                }
                if (column.field == "TermPoint" || column.field == "MovingAvg") {
                    column.template = `<input data-bind='value: ${column.field}' data-role='numerictextbox'>`;
                }
                if (column.field == "TLP") {
                    column.template = `<input data-bind='value: TLP' data-role='textbox'>`;
                }
            });
            grid.bind("dataBound", onDataBound);
            grid.setOptions({ columns: currentColumns });
        } else {
            $("#editBtn .k-button-text").text("Edit");
        }
    }

    function onDataBound(e) {
        var grid = e.sender;
        var rows = grid.tbody.children();
        var dataItems = grid.dataSource.view();
        for (var i = 0; i < dataItems.length; i++) {
            kendo.bind(rows[i], dataItems[i]); //Bind the data item to the row editors
        }
    }

4) Within the Click event of the "Edit" button, when the button is clicked again and its label is changed back to "Edit", get all selected rows and store their data items in an array. Parse the array to json and send the data items through an Ajax request to the server, where you can update them in the database. When the request is completed successfully, update back the templates of the columns, so they can be rendered as read-only.

    function onClickEdit(e) {
        var grid = $("#grid").data("kendoGrid");
        if ($("#editBtn .k-button-text").text() == "Edit") {
            $("#editBtn .k-button-text").text("Update");
            ...
        } else {
            $("#editBtn .k-button-text").text("Edit");

            var editedRecords = [];
            var selectedRows = grid.select();
            if (selectedRows.length > 0) {
                for (i = 0; i < selectedRows.length; i++) {
                    editedRecords.push(grid.dataItem(selectedRows[i])); //Store the data items of the selected rows
                }

                var models = JSON.parse(JSON.stringify({ editedRecords })); //parse the data items to JSON
                $.ajax({
                    url:  '@Url.Action("SaveRecords", "Grid")',
                    type: "POST",
                    datatype: "json",
                    data: models,
                    success: function (data) {
                        updateColumnTemplates(grid);
                        grid.dataSource.read(); // Call the Read action to load the updated data
                    }
                });
            } else {
                updateColumnTemplates(grid);
            }
        }
    }

    function updateColumnTemplates(grid) {
        var currentColumns = grid.columns;
        $.each(currentColumns, function (idx, column) {
            if (column.template != null) {
                column.template = null;
            }
        });
        grid.setOptions({ columns: currentColumns });
    }

//GridController.cs
[HttpPost]
public JsonResult SaveRecords(List<GridViewModel> editedRecords) //Receive a List with the selected data items
{
    // save the data
    return Json(true);
}

I hope this example will help you to achieve the desired result. If any questions arise, please let me know.

Regards,
Mihaela
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
Button Grid Toolbar
Asked by
abdul
Top achievements
Rank 1
Iron
Answers by
Mihaela
Telerik team
Share this question
or