Skip to main content

Batch Edit

  • 8 minutes to read

Note

Starting from v18.2, the GridView supports callbacks in batch edit mode.

The ASP.NET MVC GridView extension allows you to modify a batch of grid data on the client side and send it to the server in a single request. This topic describes how to enable batch data editing operations within your GridView. It also provides an overview of batch edit, together with a description of its limitations.

Overview

In batch edit mode, grid data contained in a page can be edited using in-line editors. All user changes are maintained on the client side until either the Save changes button is clicked or all changes are canceled by clicking the Cancel changes button.

To prevent an end-user from editing column cells, set the column’s GridColumnEditFormSettings.Visible property to false (using MVCxGridViewColumn.EditFormSettings.Visible). In this case, the column cells cannot be switched to edit mode. When an end-user navigates through cells using the TAB key, the column’s cells are skipped.

BatchEditMode

If a grid contains unsaved data, it displays a “confirm” message before a grid callback is performed. The following list provides confirmation window settings.

Property (MVC) Property (Web Forms) Description
GridViewSettings.SettingsText.ConfirmOnLosingBatchChanges ASPxGridTextSettings.ConfirmOnLosingBatchChanges Specifies the confirmation message text.
GridViewSettings.SettingsEditing.BatchEditSettings.ShowConfirmOnLosingChanges GridBatchEditSettings.ShowConfirmOnLosingChanges Specifies whether to display the confirmation window.

The GridViewBatchEditSettings.EditMode property (using GridViewSettings.SettingsEditing.BatchEditSettings.EditMode) allows you to specify which control element (data cell or data row) is used to edit data.

Enabling Batch Data Editing in the GridView

You can enable batch editing operations within the GridView in the following way.

  1. Add a controller action method that will implement the following data record operations: add new records, save updated records and delete existing records within a data source.

    This controller action method obtains an MVCxGridViewBatchUpdateValues<T, S> object as a parameter. The MVCxGridViewBatchUpdateValues<T, S> object contains the following items.

    Item Description
    MVCxBatchUpdateValues<T, S>.DeleteKeys Contains a list of keys that correspond to grid records deleted on the client side in batch edit mode.
    MVCxBatchUpdateValues<T, S>.EditorErrors Provides access to the data source items’ dictionary and the corresponding ModelStateDictionary items.
    MVCxBatchUpdateValues<T, S>.Insert Contains a list of objects that are the grid records added on the client side in batch edit mode.
    MVCxBatchUpdateValues<T, S>.Update Contains a list of grid data items updated on the client side in batch edit mode.

    The action method should apply all changes obtained from the client side to the data source and return the GridView’s Partial View.

    Controller code (“HomeController”):

    using System;
    using System.Linq;
    using System.Web.Mvc;
    using DevExpress.Web.Mvc;
    using MyProject.Models;
    
    namespace MyProject.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            MyProject.Models.Entities db = new MyProject.Models.Entities();
    
            [ValidateInput(false)]
            public ActionResult GridViewPartial()
            {
                var model = db.Customers;
                return PartialView("_GridViewPartial", model.ToList());
            }
            // Apply all changes made on the client side to a data source.
            [HttpPost, ValidateInput(false)]
            public ActionResult BatchEditingUpdateModel(MVCxGridViewBatchUpdateValues<Customer, object> updateValues)
            {
                var model = db.Customers;
                // Insert all added values.
                foreach (var customer in updateValues.Insert)
                {
                    if (updateValues.IsValid(customer))
                    {
                        try
                        {
                            model.Add(customer);
                            db.SaveChanges();
                        }
                        catch (Exception e)
                        {
                            updateValues.SetErrorText(customer, e.Message);
                        }
                    }
                }
                // Update all edited values.
                foreach (var customer in updateValues.Update)
                {
                    if (updateValues.IsValid(customer))
                    {
                        try
                        {
                            var modelItem = model.FirstOrDefault(it => it.CustomerID == customer.CustomerID);
                            if (modelItem != null)
                            {
                                this.UpdateModel(modelItem);
                                db.SaveChanges();
                            }
                        }
                        catch (Exception e)
                        {
                            updateValues.SetErrorText(customer, e.Message);
                        }
                    }
                }
                // Delete all values that were deleted on the client side from the data source.
                foreach (var customerID in updateValues.DeleteKeys)
                {
                    try
                    {
                        var item = model.FirstOrDefault(it => it.CustomerID == customerID);
                        if (item != null) model.Remove(item);
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        updateValues.SetErrorText(customerID, e.Message);
                    }
                }
                return PartialView("_GridViewPartial", model.ToList());
            }
        }
    }
    
  2. Define the callback route values within the PartialView.

    Navigate to the Partial View that contains GridView code. In the grid settings, define the callback route value to the action method (see previous step) that will handle grid callbacks for batch data modification. Set the ASPxGridViewEditingSettings.Mode property to Batch.

    Note

    Use the DevExpressEditorsBinder class to get valid editor values in the MVCxGridViewEditingSettings.BatchUpdateRouteValues method. Refer to the Binding Data Editors to Data topic for more information.

    Partial View code (“_GridViewPartial”):

    @{
        var grid = Html.DevExpress().GridView(settings => {
            settings.Name = "GridView";
            settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" };
            // Specify the route value to the action method that will handle grid callbacks for batch data modification.
            settings.SettingsEditing.BatchUpdateRouteValues = new { Controller = "Home", Action = "BatchEditingUpdateModel" };
            settings.SettingsEditing.Mode = GridViewEditingMode.Batch;
            // ...
        });
    }
    @grid.Bind(Model).GetHtml()
    

    Note that it’s necessary to assign DevExpressEditorsBinder to the ModelBinders.Binders.DefaultBinder property to replace the global default model binder.

    Global.asax:

    protected void Application_Start(){
        ...            
        ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder();
    }
    
  3. Enable the command column and command items.

    To allow end-users to manipulate grid data, add a command column to the grid’s column collection and specify which commands (New, Delete) can be used by end-users.

    Partial View code (“_GridViewPartial”):

    @{
        var grid = Html.DevExpress().GridView(settings =>
        {
            settings.Name = "myGridView";
            settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" };
            settings.SettingsEditing.BatchUpdateRouteValues = new { Controller = "Home", Action = "BatchEditingUpdateModel" };
            settings.SettingsEditing.Mode = GridViewEditingMode.Batch;
    
            settings.CommandColumn.Visible = true;
            settings.CommandColumn.ShowNewButtonInHeader = true;
            settings.CommandColumn.ShowDeleteButton = true;
    
            settings.KeyFieldName = "CustomerID";
            settings.Columns.Add("CustomerID");
            settings.Columns.Add("CompanyName");
            settings.Columns.Add("ContactName");
            settings.Columns.Add("ContactTitle");
            settings.Columns.Add("Phone");
        });
    }
    @grid.Bind(Model).GetHtml()
    

Preview changes before saving

You can preview and modify inserted, deleted and edited rows before you click the “Update” button and the control sends these changes to the server.

Set the GridViewBatchEditSettings.KeepChangesOnCallbacks property to true to show the “Show changes” button. This button allows you to display modified rows grouped by user operation type (delete, add, edit) and modify them. The “Save changes” or “Cancel changes” buttons allow you to end batch editing and save/cancel changes. To close the Changes Preview mode and display all grid rows (including modified ones), click “Hide changes”.

@Html.DevExpress().GridView(settings => {
    settings.Name = "gridView";
    settings.KeyFieldName = "ProductID";
    ...
    settings.SettingsEditing.BatchEditSettings.KeepChangesOnCallbacks = true;
    ...
}).Bind(Model).GetHtml()

By default, the grid displays only command items that allow you to edit data when the grid is in Changes Preview mode:

Command Items

To display other command items (including custom and templated items) in Changes Preview mode, set a command item’s VisibleInBatchEditPreviewChanges property to true.

@(Html.DevExpress().GridView<EditableProduct>(settings => {
    settings.Name = "grid";
    settings.Toolbars.Add(tb => {
        tb.Enabled = true;
        tb.Items.Add(i => {
            i.Text = "Export to PDF";
            i.Name = "CustomExportToPDF";
            i.VisibleInBatchEditPreviewChanges = true;
        });
        ...
    });
}).Bind(Model).GetHtml())

To customize the grid in Changes Preview mode, you can override the .dxgvBECP CSS class.

Note

The GridView supports adaptivity in Preview Changes mode.

View Example: How to enable or disable the cell edit functionality in batch mode based on a condition

View Example: How to cancel editing conditionally in batch edit mode

View Example: How to calculate values dynamically in batch edit mode

View Example: Implement cascading combo boxes in batch edit mode

Appearance Customization

You can customize the visual presentation of modified data items using the following settings available through the GridViewSettings.Styles property.

The grid stores the Update and Cancel buttons within its status bar. Use the status bar‘s style settings to control these buttons appearance.

The following code snippets illustrate how to hide the Update and Cancel buttons.

  • Using the ASPxGridSettings.ShowStatusBar property.

    @{
        var grid = Html.DevExpress().GridView(settings => {
        ...
            settings.Settings.ShowStatusBar = GridViewStatusBarMode.Hidden;
        ...
        });
    }
    @grid.Bind(Model).GetHtml()
    
  • Modifying the grid’s dxgvStatusBar CSS class.

    .dxgvStatusBar {
        display: none;
    }
    

View Example: How to implement custom buttons in the status bar in batch edit mode

Batch Edit Mode Limitations

There are features and API members of the GridView extension control are not in effect in batch edit mode, since all user changes are maintained on the client side.

Unsupported features

The features below are not supported when the grid is in batch edit mode.

Unsupported server-side API

The following server-side events are not in effect when the grid is in batch edit mode.

The ValidationSettings.SetFocusOnError property has no effect because errors are handled at the row/cell level. Use the GridBatchEditSettings.AllowEndEditOnValidationError property to keep the editor focused until an end-user inputs the correct value. For more information on validating grid data in batch edit mode, refer to the following topic: Validation in batch edit mode.

See Also