Features

Editing

Editing

This sample shows how to edit cell data with various ways.

Features

Editing

Excel-Style editing

The MultiRow has built-in support for Excel-like, fast, in-cell editing. There is no need to add extra columns with 'Edit' buttons that switch between display and edit modes.

Users can start editing simply by typing into any cell. This is called 'quick-edit' mode. In this mode, the cursor keys finish the editing and the grid moves the selection. They can also start editing by pressing F2 or by clicking a cell twice. This is called 'full-edit' mode. In this mode, the cursor keys move the caret within the editor and the user must press the Enter, Tab, or Escape keys to finish editing.

You can disable editing at the grid or column levels using the isReadOnly property of the grid or column objects.

Mobile Devices: Mobile devices use the double-click event to zoom in and out, and do not show a keyboard by default. To start editing a cell on mobile devices, simply click a cell to select it, then click it again to indicate you want to start editing.

Automatic type Validation/Coercion: If the user types anything that is invalid for the column (e.g. "hello" for a numeric or date column), the edits won't be applied and the cell will keep its original value. Dates and times are parsed using the format assigned to the column.

Checkboxes: By default (and unlike Excel), Boolean values are shown as checkboxes. Users can change the checkbox values by clicking or by pressing the space bar. Checkboxes are easier to read and to edit than fields containing "TRUE" or "FALSE" strings.

Editing Mode: There are two modes for updating the data. By default, the update operation will be commit to the server once finishing editing. If the user wants to commit the update operation to datasource server, the Update, Delete or Create action url should be provided. And the corresponding codes used to update the datasource should be written in the corresponding action. The other mode is called BatchEdit. The user can update, create or remove multiple items. Once these modifications are confirmed, They could be commit to the data source only once. Now these modifications can be commit by the commit method of CollectionView in client side. The user can also commit them by sorting, paging or filtering behavior.

Here is a typical editable MultiRow:

Popup editing

Popup editing keeps the native editing enabled for quick Excel-like data entry, and adds an "Edit Detail" button to invoke a form where the user can edit the item details.

To see this in action, select an item on the grid and click the "Edit Detail" button above. This will bring up a form where users can edit the data for the currently selected item.

The detail form uses specialized input controls that take up more space but can make data entry easier in some cases. The form has "OK" and "Cancel" buttons that commit the changes or restore the original data. Both actions are accomplished with a single call to the CollectionView used as a data source for the grid.


Inline editing

If for some reason you don't like the Excel-style editing and prefer to add editing buttons to every row (typical of editable HTML tables), you can accomplish that using an ItemFormatter and a few controller methods. To get the binding column in the ItemFormatter event handler, please use the MultiRow's getBindingColumn function.

The grid below demonstrates this approach. The buttons in the cells call methods in the controller to perform the required actions:

using C1.Web.Mvc;
using System;
using System.Linq;
using C1.Web.Mvc.Serialization;
using Microsoft.AspNetCore.Mvc;
using MultiRowExplorer.Models;
using System.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace MultiRowExplorer.Controllers
{
    public partial class MultiRowController : Controller
    {
        private readonly C1NWindEntities _db;

        public MultiRowController(C1NWindEntities db)
        {
            _db = db;
        }

        public ActionResult Editing()
        {
            return View();
        }

        public ActionResult MultiRowBindSupplier([C1JsonRequest] CollectionViewRequest<Supplier> requestData)
        {
            return this.C1Json(CollectionViewHelper.Read(requestData, _db.Suppliers.ToList()));
        }

        public ActionResult MultiRowUpdateSupplier([C1JsonRequest]CollectionViewEditRequest<Supplier> requestData)
        {
            return Update(requestData, _db.Suppliers);
        }

        public ActionResult MultiRowCreateSupplier([C1JsonRequest]CollectionViewEditRequest<Supplier> requestData)
        {
            var supplier = requestData.OperatingItems.First();
            if (supplier.CompanyName == null)
            {
                supplier.CompanyName = "";
            }

            return Create(requestData, _db.Suppliers);
        }

        public ActionResult MultiRowDeleteCategory([C1JsonRequest]CollectionViewEditRequest<Supplier> requestData)
        {
            return Delete(requestData, _db.Suppliers, item => item.SupplierID);
        }


        public ActionResult MultiRowBindCustomer([C1JsonRequest] CollectionViewRequest<Customer> requestData)
        {
            return this.C1Json(CollectionViewHelper.Read(requestData, _db.Customers.ToList()));
        }

        public ActionResult MultiRowUpdateCustomer([C1JsonRequest]CollectionViewEditRequest<Customer> requestData)
        {
            return Update(requestData, _db.Customers);
        }

        public ActionResult MultiRowCreateCustomer([C1JsonRequest]CollectionViewEditRequest<Customer> requestData)
        {
            return Create(requestData, _db.Customers);
        }

        public ActionResult MultiRowDeleteCustomer([C1JsonRequest]CollectionViewEditRequest<Customer> requestData)
        {
            return Delete(requestData, _db.Customers, item => item.CustomerID);
        }

        private ActionResult Update<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data) where T : class
        {
            return this.C1Json(CollectionViewHelper.Edit<T>(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    _db.Entry(item as object).State = EntityState.Modified;
                    _db.SaveChanges();
                }
                catch (Exception e)
                {
                    error = GetExceptionMessage(e);
                    success = false;
                }
                return new CollectionViewItemResult<T>
                {
                    Error = error,
                    Success = success,
                    Data = item
                };
            }, () => data.ToList<T>()));
        }

        private ActionResult Create<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data) where T : class
        {
            return this.C1Json(CollectionViewHelper.Edit<T>(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    data.Add(item);
                    _db.SaveChanges();
                }
                catch (Exception e)
                {
                    error = GetExceptionMessage(e);
                    success = false;
                }
                return new CollectionViewItemResult<T>
                {
                    Error = error,
                    Success = success,
                    Data = item
                };
            }, () => data.ToList<T>()));
        }

        private ActionResult Delete<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data, Func<T, object> getKey) where T : class
        {
            return this.C1Json(CollectionViewHelper.Edit(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    T resultItem = null;
                    foreach (var i in data)
                    {
                        if (string.Equals(getKey(i).ToString(), getKey(item).ToString()))
                        {
                            resultItem = i;
                            break;
                        }
                    }

                    if (resultItem != null)
                    {
                        data.Remove(resultItem);
                        _db.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    error = GetExceptionMessage(e);
                    success = false;
                }
                return new CollectionViewItemResult<T>
                {
                    Error = error,
                    Success = success,
                    Data = item
                };
            }, () => data.ToList()));
        }

        /// <summary>
        /// In order to get the real exception message.
        /// </summary>
        private static SqlException GetSqlException(Exception e)
        {
            while (e != null && !(e is SqlException))
            {
                e = e.InnerException;
            }
            return e as SqlException;
        }

        // Get the real exception message
        internal static string GetExceptionMessage(Exception e)
        {
            var msg = e.Message;
            var sqlException = GetSqlException(e);
            if (sqlException != null)
            {
                msg = sqlException.Message;
            }
            return msg;
        }
    }
}
@model C1NWindEntities
@{
    ViewBag.DemoDescription = false;
}

@section Scripts{
    <script type="text/javascript" src="~/Scripts/jquery.js"></script>
    <script type="text/javascript" src="~/Scripts/BootStrap/bootstrap.js"></script>

    <script>
        var editMultiRow, editCV,
            showEditDialogBtn,
            idInput, companyNameInput, contactNameInput, contactTitleInput, countryInput, regionInput, cityInput, addressInput;

        c1.documentReady(function () {
            editMultiRow = wijmo.Control.getControl('#editMultiRow');
            editCV = editMultiRow.collectionView;
            showEditDialogBtn = document.getElementById('showEditDialogBtn');
            idInput = document.getElementById('SupplierID');
            companyNameInput = document.getElementById('CompanyName');
            contactNameInput = document.getElementById('ContactName');
            contactTitleInput = document.getElementById('ContactTitle');
            countryInput = document.getElementById('Country');
            regionInput = document.getElementById('Region');
            cityInput = document.getElementById('City');
            addressInput = document.getElementById('Address');

            updateButton();
            editCV.currentChanged.addHandler(updateButton);
        });
        function showEditDialog() {
            var current;

            if (!editCV || !editCV.currentItem) {
                return;
            }
            current = editCV.currentItem;
            // fill the current item data to the inputs.
            idInput.value = current.SupplierID;
            companyNameInput.value = current.CompanyName;
            contactNameInput.value = current.ContactName;
            contactTitleInput.value = current.ContactTitle;
            countryInput.value = current.Country;
            regionInput.value = current.Region;
            cityInput.value = current.City;
            addressInput.value = current.Address;
        }
        function updateButton() {
            if (!showEditDialogBtn) {
                return;
            }
            if (!editCV || !editCV.currentItem) {
                showEditDialogBtn.disabled = true;
            } else {
                showEditDialogBtn.disabled = false;
            }
        }
        function commitUpdate() {
            if (!editCV) {
                return;
            }

            var editItem = editCV.currentItem;

            // begin to edit the current item
            editCV.editItem(editItem);

            //update the data
            editItem.CompanyName = companyNameInput.value;
            editItem.ContactName = contactNameInput.value;
            editItem.ContactTitle = contactTitleInput.value;
            editItem.Country = countryInput.value;
            editItem.Region = regionInput.value;
            editItem.City = cityInput.value;
            editItem.Address = addressInput.value;
            // commit the edit
            editCV.commitEdit();
        }

        var inlineEditMultiRow, inlineEditCV,
            editIndex = -1;
        c1.documentReady(function () {
            inlineEditMultiRow = wijmo.Control.getControl('#inlineEditMultiRow');
            inlineEditMultiRow.rows.defaultSize = 50;
            inlineEditCV = inlineEditMultiRow.collectionView;
        });
        function itemFormatter(panel, r, c, cell) {
            var col, html, hasUpdated = false;
            var rowIndex = Math.floor(r / panel.grid.rowsPerItem);
            if (panel.cellType == wijmo.grid.CellType.Cell) {
                col = panel.grid.getBindingColumn(panel, r, c);
                if (rowIndex == editIndex) {
                    switch (col.name) {
                        case "CustomerID":
                            break;
                        case 'Buttons':
                            html = '<div>' +
                                   '&nbsp;&nbsp;' +
                                   '<button class="btn btn-primary btn-sm" style="width:80px;" onclick="commitRow(' + rowIndex + ')">' +
                                       '<span class="glyphicon glyphicon-ok"></span> OK' +
                                   '</button>' +
                                   '<br/>&nbsp;&nbsp;' +
                                   '<button class="btn btn-warning btn-sm" style="width:80px;" onclick="cancelRow(' + rowIndex + ')">' +
                                       '<span class="glyphicon glyphicon-ban-circle"></span> Cancel' +
                                   '</button>' +
                               '</div>';
                            hasUpdated = true;
                            break;
                        default:
                            var theId = "the" + col.name;
                            html = '<input id="' + theId + '" class="form-control" onkeydown="keyDown(event)" value="' + panel.getCellData(r, c, true) + '"/>';
                            hasUpdated = true;
                            break;
                    }
                }
                else {
                    switch (col.name) {
                        case 'Buttons':
                            hasUpdated = true;
                            html = '<div>' +
                                   '&nbsp;&nbsp;' +
                                   '<button class="btn btn-default btn-sm" style="width:80px;" onclick="editRow(' + rowIndex + ')">' +
                                       '<span class="glyphicon glyphicon-pencil"></span> Edit' +
                                   '</button>' +
                                   '<br/>&nbsp;&nbsp;' +
                                   '<button class="btn btn-default btn-sm" style="width:80px;" onclick="deleteRow(' + rowIndex + ')">' +
                                       '<span class="glyphicon glyphicon-remove"></span> Delete' +
                                   '</button>' +
                               '</div>';
                            break;
                    }
                }
                if (hasUpdated) {
                    cell.innerHTML = html;
                    cell.style.padding = '3px';
                }
            }
        }
        function keyDown(e) {
            e.stopPropagation();
        }
        function editRow(rowIndex) {
            if (!inlineEditMultiRow || !inlineEditCV) {
                return;
            }
            editIndex = rowIndex;
            inlineEditMultiRow.invalidate();
        }
        function deleteRow(rowIndex) {
            if (!inlineEditCV) {
                return;
            }
            editIndex = -1;
            inlineEditCV.removeAt(rowIndex);
        }
        function commitRow(rowIndex) {
            var countryInput, addressInput, editItem;
            if (!inlineEditCV) {
                return;
            }
            //update the data
            inlineEditCV.editItem(inlineEditCV.items[rowIndex]);
            editItem = inlineEditCV.currentEditItem;
            if (!editItem) {
                return;
            }
            editItem.CompanyName = document.getElementById('theCompanyName').value;
            editItem.ContactName = document.getElementById('theContactName').value;
            editItem.ContactTitle = document.getElementById('theContactTitle').value;
            editItem.Country = document.getElementById('theCountry').value;
            editItem.Region = document.getElementById('theRegion').value;
            editItem.City = document.getElementById('theCity').value;
            editItem.Address = document.getElementById('theAddress').value;
            editIndex = -1;
            inlineEditCV.commitEdit();
        }

        function cancelRow() {
            editIndex = -1;
            inlineEditMultiRow.invalidate();
        }
    </script>
}

@section Summary{
    This sample shows how to edit cell data with various ways.
}

<h3>
    Editing
</h3>

<h4>
    Excel-Style editing
</h4>
<p>
    The <b>MultiRow</b> has built-in support for Excel-like, fast, in-cell editing.
    There is no need to add extra columns with 'Edit' buttons that switch
    between display and edit modes.
</p>
<p>
    Users can start editing simply by typing into any cell. This is called 'quick-edit' mode.
    In this mode, the cursor keys finish the editing and the grid moves the selection.
    They can also start editing by pressing F2 or by clicking a cell twice.
    This is called 'full-edit' mode.
    In this mode, the cursor keys move the caret within the editor and the user must
    press the Enter, Tab, or Escape keys to finish editing.
</p>
<div class="collapsed-content collapse">
    <p>
        You can disable editing at the grid or column levels using the <b>isReadOnly</b>
        property of the grid or column objects.
    </p>
    <p>
        <b>Mobile Devices:</b>
        Mobile devices use the double-click event to zoom in and out, and do not show
        a keyboard by default. To start editing a cell on mobile devices, simply click
        a cell to select it, then click it again to indicate you want to start editing.
    </p>
    <p>
        <b>Automatic type Validation/Coercion:</b>
        If the user types anything that is invalid for the column (e.g. "hello" for a
        numeric or date column), the edits won't be applied and the cell will keep its
        original value. Dates and times are parsed using the format assigned to the
        column.
    </p>
    <p>
        <b>Checkboxes:</b>
        By default (and unlike Excel), Boolean values are shown as checkboxes. Users
        can change the checkbox values by clicking or by pressing the space bar.
        Checkboxes are easier to read and to edit than fields containing "TRUE" or
        "FALSE" strings.
    </p>
    <p>
        <b>Editing Mode:</b>
        There are two modes for updating the data.
        By default, the update operation will be commit to the server once finishing editing.
        If the user wants to commit the update operation to datasource server, the Update, Delete or Create action url should be provided.
        And the corresponding codes used to update the datasource should be written in the corresponding action.
        The other mode is called <b>BatchEdit</b>. The user can update, create or remove multiple items.
        Once these modifications are confirmed, They could be commit to the data source only once.
        Now these modifications can be commit by the <b>commit</b> method of <b>CollectionView</b> in client side.
        The user can also commit them by sorting, paging or filtering behavior.
    </p>
</div>

<p>
    <input type="button" value="Read More" class="btn collapse in" data-toggle="collapse" data-target=".collapsed-content, .btn.collapse" />
</p>

<p>
    Here is a typical editable MultiRow:
</p>

<c1-multi-row id="editMultiRow" allow-add-new="true" allow-delete="true" class="multirow">
    <c1-items-source read-action-url="@Url.Action("MultiRowBindSupplier")"
                     update-action-url="@Url.Action("MultiRowUpdateSupplier")"
                     create-action-url="@Url.Action("MultiRowCreateSupplier")"
                     delete-action-url="@Url.Action("MultiRowDeleteSupplier")"></c1-items-source>
    <c1-multi-row-cell-group>
        <c1-multi-row-cell binding="SupplierID" is-read-only="true" format="d" align="center"></c1-multi-row-cell>
    </c1-multi-row-cell-group>
    <c1-multi-row-cell-group colspan="2">
        <c1-multi-row-cell binding="CompanyName" colspan="2"></c1-multi-row-cell>
        <c1-multi-row-cell binding="ContactName" width="150"></c1-multi-row-cell>
        <c1-multi-row-cell binding="ContactTitle" width="200"></c1-multi-row-cell>
    </c1-multi-row-cell-group>
    <c1-multi-row-cell-group colspan="3">
        <c1-multi-row-cell binding="Country"></c1-multi-row-cell>
        <c1-multi-row-cell binding="Region"></c1-multi-row-cell>
        <c1-multi-row-cell binding="City"></c1-multi-row-cell>
        <c1-multi-row-cell binding="Address" colspan="3"></c1-multi-row-cell>
    </c1-multi-row-cell-group>
</c1-multi-row>

<!-- a dialog for editing item details -->
<div class="modal fade" id="dlgDetail">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button"
                        class="close"
                        data-dismiss="modal"
                        aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title">Edit Item</h4>
            </div>
            <div class="modal-body">
                <dl class="dl-horizontal">
                    <dt>Supplier ID</dt>
                    <dd>
                        <input id="SupplierID" class="form-control" disabled />
                    </dd>
                    <dt>Company Name</dt>
                    <dd>
                        <input id="CompanyName" class="form-control" />
                    </dd>
                    <dt>Contact Name</dt>
                    <dd>
                        <input id="ContactName" class="form-control" />
                    </dd>
                    <dt>Contact Title</dt>
                    <dd>
                        <input id="ContactTitle" class="form-control" />
                    </dd>
                    <dt>Country</dt>
                    <dd>
                        <input id="Country" class="form-control" />
                    </dd>
                    <dt>Region</dt>
                    <dd>
                        <input id="Region" class="form-control" />
                    </dd>
                    <dt>City</dt>
                    <dd>
                        <input id="City" class="form-control" />
                    </dd>
                    <dt>Address</dt>
                    <dd>
                        <input id="Address" class="form-control" />
                    </dd>
                </dl>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal"
                        onclick="commitUpdate()">
                    <span class="glyphicon glyphicon-ok"></span>
                    OK
                </button>
                <button type="button" class="btn btn-warning" data-dismiss="modal">
                    <span class="glyphicon glyphicon-ban-circle"></span>
                    Cancel
                </button>
            </div>
        </div><!-- modal-content -->
    </div><!-- modal-dialog -->
</div><!-- modal -->

<div class="well grid-sort-group">

    <!-- edit details in a popup -->
    <button id="showEditDialogBtn"
            class="btn btn-default"
            data-toggle="modal"
            data-backdrop="static"
            data-keyboard="false"
            data-target="#dlgDetail"
            onclick="showEditDialog()">
        <span class="glyphicon glyphicon-new-window"></span>
        Edit Detail...
    </button>
</div>

<h4>
    Popup editing
</h4>
<p>
    Popup editing keeps the native editing enabled for quick Excel-like data entry, and adds
    an "Edit Detail" button to invoke a form where the user can edit the item details.
</p>
<p>
    To see this in action, select an item on the grid and click the "Edit Detail" button above.
    This will bring up a form where users can edit the data for the currently selected item.
</p>
<p>
    The detail form uses specialized input controls that take up more space but can make data
    entry easier in some cases. The form has "OK" and "Cancel" buttons that commit the changes
    or restore the original data. Both actions are accomplished with a single call to the
    <b>CollectionView</b> used as a data source for the grid.
</p>
<br />
<h4>
    Inline editing
</h4>
<p>
    If for some reason you don't like the Excel-style editing and prefer to add editing
    buttons to every row (typical of editable HTML tables), you can accomplish that
    using an <b>ItemFormatter</b> and a few controller methods.
    To get the binding column in the ItemFormatter event handler, please use the MultiRow's
    <b>getBindingColumn</b> function.
</p>
<p>
    The grid below demonstrates this approach. The buttons in the cells call
    methods in the controller to perform the required actions:
</p>

<c1-multi-row id="inlineEditMultiRow" is-read-only="true" selection-mode="None"
              class="multirow" item-formatter="itemFormatter">
    <c1-items-source read-action-url="@Url.Action("MultiRowBindCustomer")"
                     update-action-url="@Url.Action("MultiRowUpdateCustomer")"
                     create-action-url="@Url.Action("MultiRowCreateCustomer")"
                     delete-action-url="@Url.Action("MultiRowDeleteCustomer")"></c1-items-source>
    <c1-multi-row-cell-group>
        <c1-multi-row-cell binding="CustomerID" name="CustomerID" header="ID" width="80" align="center" is-read-only="true"></c1-multi-row-cell>
    </c1-multi-row-cell-group>
    <c1-multi-row-cell-group colspan="2">
        <c1-multi-row-cell binding="CompanyName" name="CompanyName" colspan="2"></c1-multi-row-cell>
        <c1-multi-row-cell binding="ContactName" name="ContactName" width="150"></c1-multi-row-cell>
        <c1-multi-row-cell binding="ContactTitle" name="ContactTitle" width="150"></c1-multi-row-cell>
    </c1-multi-row-cell-group>
    <c1-multi-row-cell-group colspan="3">
        <c1-multi-row-cell binding="Country" name="Country" width="80"></c1-multi-row-cell>
        <c1-multi-row-cell binding="Region" name="Region" width="80"></c1-multi-row-cell>
        <c1-multi-row-cell binding="City" name="City"></c1-multi-row-cell>
        <c1-multi-row-cell binding="Address" name="Address" colspan="3"></c1-multi-row-cell>
    </c1-multi-row-cell-group>
    <c1-multi-row-cell-group>
        <c1-multi-row-cell name="Buttons" width="100"></c1-multi-row-cell>
    </c1-multi-row-cell-group>
</c1-multi-row>