Data Editing

  • 6 min to read

The ASP.NET MVC GridView provides built-in data editing functionality. This topic describes how to enable data editing operations within the GridView.

Requirements

To follow the steps described in this topic, you will need a data-bound GridView extension in your project.

Enabling Data Editing within the GridView

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

  1. Add the controller action method that will add new records to a data source.

    This controller action method obtains a newly added object as a parameter. The action method should implement the functionality to add a new record and return the GridView's Partial View.

    Controller code ("HomeController"):

    
    // Handle grid callbacks for adding a new record.
    [HttpPost, ValidateInput(false)]
    public ActionResult GridViewPartialAddNew(WebApplicationEFTest.Models.Customer item)
    {
        var model = db.Customers;
        // Performs server-side model validation based on data annotation attributes.
        if (ModelState.IsValid)
        {
            try
            {
                // Adds a new item to a data source via the Entity Framework.
                model.Add(item);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                // If an exception occurs, ViewBag passes an error message to the grid's partial view and defines the grid's error text.
                ViewBag.EditError = e.Message;
            }
        }
        else
            ViewBag.EditError = "Please, correct all errors.";
       // Return the grid's Partial View with a data model.
       return PartialView("_GridViewPartial", model.ToList());
    }
    
  2. Add the controller action method that will save the updated records to a data source.

    This controller action method obtains an edited object as a parameter. The action method should implement the functionality to update records and return the GridView's Partial View.

    Controller code ("HomeController"):

    
    // Handle grid callbacks for updating an edited record.
    [HttpPost, ValidateInput(false)]
    public ActionResult GridViewPartialUpdate(WebApplicationEFTest.Models.Customer item)
    {
        var model = db.Customers;
        // Performs server-side model validation based on data annotation attributes.
        if (ModelState.IsValid)
        {
            try
            {
                // Updates an item within a data source via the Entity Framework.
                var modelItem = model.FirstOrDefault(it => it.CustomerID == item.CustomerID);
                if (modelItem != null)
                {
                    this.UpdateModel(modelItem);
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                // If an exception occurs, ViewBag passes an error message to the grid's partial view and defines the grid's error text.
                ViewBag.EditError = e.Message;
            }
        }
        else
            ViewBag.EditError = "Please, correct all errors.";
        // Return the grid's Partial View with a data model.
        return PartialView("_GridViewPartial", model.ToList());
    }
    
  3. Add the controller action method that will delete existing records from a data source.

    This controller action method obtains the key value of the record to delete. The action method should implement the functionality to delete records and return the GridView's Partial View.

    Controller code ("HomeController"):

    
    // Handle grid callbacks for deleting a record.
    [HttpPost, ValidateInput(false)]
    public ActionResult GridViewPartialDelete(System.String CustomerID)
    {
        var model = db.Customers;
        if (CustomerID != null)
        {
            try
            {
                // Removes an item from a data source via the Entity Framework.
                var item = model.FirstOrDefault(it => it.CustomerID == CustomerID);
                if (item != null)
                    model.Remove(item);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                // If an exception occurs, ViewBag passes an error message to the grid's partial view and defines the grid's error text.
                ViewBag.EditError = e.Message;
            }
        }
        // Return the grid's Partial View with a data model.
        return PartialView("_GridViewPartial", model.ToList());
    }
    
  4. Define the callback route values within the PartialView.

    Navigate to the Partial View that contains the GridView code. In the grid settings, define the callback route values to the action methods (created above), which will handle grid callbacks for adding, updating and deleting records.

    Partial View code ("_GridViewPartial"):

    
    @{
        var grid = Html.DevExpress().GridView(settings => {
            settings.Name = "GridView";
            settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" };
            // Callback route values to the action methods, which will handle grid callbacks for adding, updating and deleting records.
            settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "GridViewPartialAddNew" };
            settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "GridViewPartialUpdate" };
            settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "GridViewPartialDelete" };
            // ...
        });
        if (ViewBag.EditError != null)
        {
            grid.SetEditErrorText(ViewBag.EditError);
        }
    }
    @grid.Bind(Model).GetHtml()
    
  5. 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, Edit, Delete, Update, Cancel) can be used by end-users. To switch a grid row to edit mode, end-users should be allowed to click the Edit command.

    Partial View code ("_GridViewPartial"):

    
    @{
        var grid = Html.DevExpress().GridView(settings => {
            settings.Name = "GridView";
            settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" };
    
            settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "GridViewPartialAddNew" };
            settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "GridViewPartialUpdate" };
            settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "GridViewPartialDelete" };
            // Enable a command column.
            settings.CommandColumn.Visible = true;
            settings.CommandColumn.ShowNewButton = true;
            settings.CommandColumn.ShowDeleteButton = true;
            settings.CommandColumn.ShowEditButton = true;
    
            settings.KeyFieldName = "CustomerID";
            settings.Columns.Add("CompanyName");
            settings.Columns.Add("ContactName");
            settings.Columns.Add("ContactTitle");
            settings.Columns.Add("Phone");
        });
        if (ViewBag.EditError != null)
        {
            grid.SetEditErrorText(ViewBag.EditError);
        }
    }
    @grid.Bind(Model).GetHtml()
    

    Note that in addition to the built-in edit form, you can add, edit and delete grid records using the grid's client-side API.

Editing GridView via the Client-Side API

GridView provides a full-featured client-side API that allows you to manipulate the edit form via JS code. The table below lists the available data editing-related methods.

Method Description
ASPxClientGridView.AddNewRow (via MVCxClientGridView.AddNewRow) Adds a new record.
ASPxClientGridView.StartEditRow (via MVCxClientGridView.StartEditRow) Opens an edit form for editing a specified row.
ASPxClientGridView.StartEditRowByKey (via MVCxClientGridView.StartEditRowByKey) Opens an edit form for editing a row with the specified key.
ASPxClientGridView.SetEditValue (via MVCxClientGridView.SetEditValue) Sets the value of the specified edit cell.
ASPxClientGridView.IsNewRowEditing (via MVCxClientGridView.IsNewRowEditing) Indicates whether or not a new row is being edited.
ASPxClientGridView.IsEditing (via MVCxClientGridView.IsEditing) Indicates whether or not the GridView extension is in edit mode.
ASPxClientGridView.UpdateEdit (via MVCxClientGridView.UpdateEdit) Saves all changes made and switches the GridView extension to browse mode.
ASPxClientGridView.CancelEdit (via MVCxClientGridView.CancelEdit) Cancels all changes made and switches the GridView extension to browse mode.
ASPxClientGridView.DeleteRow (via MVCxClientGridView.DeleteRow) Deletes the specified row.
ASPxClientGridView.DeleteRowByKey (via MVCxClientGridView.DeleteRowByKey) Deletes a row with the specified key value.

Example

In this example, the ASPxClientGridView.RowDblClick (via MVCxClientGridView.RowDblClick) client-side event is handled to switch the GridView to edit mode by double-clicking a data row. The event handler calls the ASPxClientGridView.StartEditRow (via MVCxClientGridView.StartEditRow) method. This method receives the visible index of the double-clicked row and invokes an edit form.


@{
    var grid = Html.DevExpress().GridView(settings => {
        settings.Name = "GridView";
        settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" };

        settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "GridViewPartialAddNew" };
        settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "GridViewPartialUpdate" };
        settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "GridViewPartialDelete" };

        settings.CommandColumn.Visible = true;
        settings.CommandColumn.ShowNewButton = true;
        settings.CommandColumn.ShowDeleteButton = true;
        settings.CommandColumn.ShowEditButton = true;

        settings.KeyFieldName = "CustomerID";
        settings.Columns.Add("CompanyName");
        settings.Columns.Add("ContactName");
        settings.Columns.Add("ContactTitle");
        settings.Columns.Add("Phone");
        // When an end-user double-clicks a grid row, the edit form appears, allowing an end-user to edit the row.
        settings.ClientSideEvents.RowDblClick = "function(s, e) { s.StartEditRow(e.visibleIndex); }";
    });
    if (ViewBag.EditError != null)
    {
        grid.SetEditErrorText(ViewBag.EditError);
    }
}
@grid.Bind(Model).GetHtml()
See Also