Batch Editing in ASP.NET MVC Grid Component

11 Jan 202310 minutes to read

In batch edit mode, when you double-click on the grid cell, then the target cell changed to edit state. You can bulk save (added, changed and deleted data in the single request) to data source by click on the toolbar’s Update button or by externally calling the batchSave method. To enable Batch edit, set the Mode of EditSettings as Batch.

@Html.EJS().Grid("BatchEdit").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("150").AllowEditing(false).ValidationRules(new { required = "true", minLength=3 }).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Batch); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

If a column’s AllowEditing property is set to false, then the focus can be skipped in that non-editable column by clicking the tab or shift-tab key while in batch edit mode.

Cancel edit based on condition in batch mode

You can prevent the CRUD operations of the Batch edit Grid by using condition in the cellEdit, beforeBatchAdd and beforeBatchDelete events for Edit, Add and Delete actions respectively.

In the below demo, we prevent the CRUD operation based on the Role column value. If the Role Column is Employee, we are unable to edit/delete that row.

<button onclick="btnClick(event)">Grid is Addable</button>
@Html.EJS().Grid("BatchEdit").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = "true" }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Role").HeaderText("Role").Width("150").Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).CellEdit("cellEdit").BeforeBatchAdd("beforeBatchAdd").BeforeBatchDelete("beforeBatchDelete").AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Batch); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()

<script>
    var isAddable = true;

    function btnClick(args) {
        args.target.innerText == 'Grid is Addable' ? (args.target.innerText = 'Grid is Not Addable') : (args.target.innerText = 'Grid is Addable');
        isAddable = !isAddable;
    }

    function cellEdit(args) {
        if (args.rowData['Role'] == 'Employee') {
            args.cancel = true;
        }
    }

    function beforeBatchAdd(args) {
        if (!isAddable) {
            args.cancel = true;
        }
    }

    function beforeBatchDelete(args) {
        if (args.rowData['Role'] == 'Employee') {
            args.cancel = true;
        }
    }

</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Confirmation dialog

By default, grid will show the confirm dialog when saving or canceling or performing any actions like filtering, sorting, etc.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = "true", minLength=3 }).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(5)).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).ShowConfirmDialog(false).ShowDeleteConfirmDialog(true).Mode(Syncfusion.EJ2.Grids.EditMode.Batch); }).Render()
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

NOTE

ShowConfirmDialog of EditSettingsrequires the Mode to be Batch.

If ShowConfirmDialog set to false, then confirmation dialog does not display in batch editing.

How to make editing in single click and arrow keys

When using batch mode, the TAB key allows you to edit or move to the next cell or row from the current record by default. Using the grid’s load event, the same functionality can also be achieved by pressing the arrow keys. Additionally, the editCell method of the grid allows for cells to be made editable with a single click.

In the following sample, the Load event of the Grid will be used to bind the keydown event handler. When any arrow key is pressed, the editCell method of the Grid will be used to identify the next or previous cell (td) and set it to be editable. Additionally, it is possible to enable editing of a cell with a single click by utilizing the editCell method within the Created event of the Grid.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowPaging().EnableHover(false).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(100).IsPrimaryKey(true).Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width(120).Add();
    col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(120).Format("C2").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width(150).Add();
}).Created("created").Load("load").EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Batch); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()

<script>
    function load(args) {
        var grid = document.getElementById('Grid').ej2_instances[0];
        grid.element.addEventListener('keydown', function (e) {
            var closesttd = (e.target).closest('td');
            if (e.keyCode === 39 && !ej.base.isNullOrUndefined(closesttd.nextSibling)) {
                editACell(closesttd.nextSibling);
            }
            if (e.keyCode === 37 && !ej.base.isNullOrUndefined(closesttd.previousSibling) &&
                !grid.getColumnByIndex(
                    parseInt(closesttd.previousSibling.getAttribute('data-colindex'))).isPrimaryKey) {
                editACell(closesttd.previousSibling);
            }
            if (e.keyCode === 40 && !ej.base.isNullOrUndefined(closesttd.closest('tr').nextSibling)) {
                editACell(
                    closesttd.closest('tr').nextSibling.querySelectorAll('td')[
                    parseInt(closesttd.getAttribute('data-colindex'))]);
            }
            if (e.keyCode === 38 && !ej.base.isNullOrUndefined(closesttd.closest('tr').previousSibling)) {
                editACell(
                    closesttd.closest('tr').previousSibling.querySelectorAll('td')[
                    parseInt(closesttd.getAttribute('data-colindex'))]);
            }
        });
    }
    function created(args) {
        var grid = document.getElementById('Grid').ej2_instances[0];
        grid.getContentTable().addEventListener('click', function (args) {
            if ((args.target).classList.contains('e-rowcell')) {
                grid.editModule.editCell(parseInt((args.target).getAttribute('index')),
                    grid.getColumnByIndex(parseInt(args.target.getAttribute('data-colindex'))).field);
            }
        });
    }
    function editACell(args) {
        var grid = document.getElementById('Grid').ej2_instances[0];
        grid.editModule.editCell(
            parseInt(args.getAttribute('index')),
            grid.getColumnByIndex(parseInt(args.getAttribute('data-colindex'))).field);
    }
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}