Features

Editing

Editing

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

Features

Editing

Excel-Style editing

The MultiRow control 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 puts the cell in 'quick-edit' mode. In this mode, pressing the cursor keys completes the editing and the grid moves the selection.

Another way to begin in-cell editing is by pressing F2 or by clicking a cell twice. This puts the cell in 'full-edit' mode. In this mode, the cursor keys move the caret within the cell text and the user must press the Enter, Tab, or Escape keys to complete editing.

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

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

Automatic Type Validation/Coercion: If the user types anything that is invalid for a 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.

Checkbox: By default (and unlike Microsoft 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.

Update Modes: The edited data gets updated to the datasource server, by default, once editing is done. This is the normal update mode, for which users need to provide the Update, the Delete or the Create action url. And the corresponding codes used to update the datasource should be written in the corresponding action. However, users can also update, create or remove multiple items and commit them to the data source only once. This is the batch update mode, for which users need to provide the BatchEditing action Url.

Here is a typical editable MultiRow:

Popup editing

Popup editing keeps the native editing enabled for quick Microsoft 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 do not need the Microsoft Excel-style editing and prefer to add editing buttons to every row (typical of editable HTML tables), you can accomplish that by using 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 the methods in the controller to perform the required actions:

using C1.Web.Mvc;
using MultiRowExplorer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using C1.Web.Mvc.Serialization;
using System.Data;
using System.Collections;
using System.Globalization;
using System.Data.Entity;
using System.Data.Entity.Validation;

namespace MultiRowExplorer.Controllers
{
    public partial class MultiRowController : Controller
    {
        private C1NWindContext db = new C1NWindContext();
        //
        // GET: /Editing/

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

        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 MultiRowDeleteSupplier([C1JsonRequest]CollectionViewEditRequest<Supplier> requestData)
        {
            return Delete(requestData, db.Suppliers, item => item.SupplierID);
        }

        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 (DbEntityValidationException e)
                {
                    error = string.Join(",", e.EntityValidationErrors.Select(result =>
                    {
                        return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage));
                    }));
                    success = false;
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }
                return new CollectionViewItemResult<T>
                {
                    Error = error,
                    Success = success && ModelState.IsValid,
                    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 (DbEntityValidationException e)
                {
                    error = string.Join(",", e.EntityValidationErrors.Select(result =>
                    {
                        return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage));
                    }));
                    success = false;
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }
                return new CollectionViewItemResult<T>
                {
                    Error = error,
                    Success = success && ModelState.IsValid,
                    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<T>(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    var resultItem = data.Find(getKey(item));
                    data.Remove(resultItem);
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    error = string.Join(",", e.EntityValidationErrors.Select(result =>
                    {
                        return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage));
                    }));
                    success = false;
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }
                return new CollectionViewItemResult<T>
                {
                    Error = error,
                    Success = success && ModelState.IsValid,
                    Data = item
                };
            }, () => data.ToList<T>()));
        }

    }
}
@model C1NWindContext
@{
    ViewBag.DemoDescription = false;
}

@section Scripts{
    @Scripts.Render("~/jquery")
    @Scripts.Render("~/BootStrapJS")

    <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> control 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 puts the cell in 'quick-edit' mode.
    In this mode, pressing the cursor keys completes the editing and the grid moves the selection.
</p>
<p>
    Another way to begin in-cell editing is by pressing F2 or by clicking a cell twice.
    This puts the cell in 'full-edit' mode. In this mode, the cursor keys move the caret within the cell text and the user must
    press the Enter, Tab, or Escape keys to complete editing.
</p>
<div class="collapsed-content collapse">
    <p><b>Disable Editing</b>
        You can disable editing at grid or column levels using the <b>isReadOnly</b>
        property of grid or column objects.
    </p>
    <p>
        <b>Mobile Devices:</b>
        Mobile devices use the <b>double-click</b> event to zoom in and out, and do not show
        keyboard by default. To start editing a cell on mobile devices, users need to simply click
        a cell to select it, then click it again to indicate they want to start editing.
    </p>
    <p>
        <b>Automatic Type Validation/Coercion:</b>
        If the user types anything that is invalid for a 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>Checkbox:</b>
        By default (and unlike Microsoft 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>Update Modes:</b>
        The edited data gets updated to the datasource server, by default, once editing is done.
        This is the normal update mode, for which users need to provide the Update, the Delete or the Create action url.
        And the corresponding codes used to update the datasource should be written in the corresponding action.
        However, users can also update, create or remove multiple items and commit them to the data source only once.
        This is the batch update mode, for which users need to provide the BatchEditing action Url.
    </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>
@(Html.C1().MultiRow<Supplier>()
    .Id("editMultiRow")
    .LayoutDefinition(ld =>
    {
        ld.Add().Cells(cells =>
        {
            cells.Add(c => c.Binding("SupplierID").IsReadOnly(true).Format("d").Align("center"));
        });
        ld.Add().Colspan(2).Cells(cells =>
        {
            cells.Add(c => c.Binding("CompanyName").Colspan(2))
            .Add(c => c.Binding("ContactName").Width("150"))
            .Add(c => c.Binding("ContactTitle").Width("200"));
        });
        ld.Add().Colspan(3).Cells(cells=>
        {
            cells.Add(c => c.Binding("Country"))
            .Add(c=>c.Binding("Region"))
            .Add(c=>c.Binding("City"))
            .Add(c=>c.Binding("Address").Colspan(3));
        });
    })
    .Bind(
        ib => ib.Bind(Model.Suppliers)
        .Update(Url.Action("MultiRowUpdateSupplier"))
        .Create(Url.Action("MultiRowCreateSupplier"))
        .Delete(Url.Action("MultiRowDeleteSupplier"))
    )
    .AllowAddNew(true)
    .AllowDelete(true)
    .CssClass("multirow")
)

<!-- 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 Microsoft 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 do not need the Microsoft Excel-style editing and prefer to add editing
    buttons to every row (typical of editable HTML tables), you can accomplish that by
    using <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 the
    methods in the controller to perform the required actions:
</p>

@(Html.C1().MultiRow<Customer>()
    .Id("inlineEditMultiRow")
    .IsReadOnly(true)
    .SelectionMode(C1.Web.Mvc.Grid.SelectionMode.None)
    .Bind(
        ib => ib.Bind(Model.Customers)
        .Update(Url.Action("MultiRowUpdateCustomer"))
        .Create(Url.Action("MultiRowCreateCustomer"))
        .Delete(Url.Action("MultiRowDeleteCustomer"))
    )
    .LayoutDefinition(ld =>
    {
        ld.Add().Cells(clsb =>
        {
            clsb.Add(cb => cb.Binding("CustomerID").Name("CustomerID").Header("ID").Width("80").Align("center").IsReadOnly(true));
        });
        ld.Add().Colspan(2).Cells(clsb =>
        {
            clsb.Add(cb => cb.Binding("CompanyName").Name("CompanyName").Colspan(2));
            clsb.Add(cb => cb.Binding("ContactName").Name("ContactName").Width("150"));
            clsb.Add(cb => cb.Binding("ContactTitle").Name("ContactTitle").Width("150"));
        });
        ld.Add().Colspan(3).Cells(clsb =>
        {
            clsb.Add(cb=>cb.Binding("Country").Name("Country").Width("80"));
            clsb.Add(cb => cb.Binding("Region").Name("Region").Width("80"));
            clsb.Add(cb => cb.Binding("City").Name("City"));
            clsb.Add(cb => cb.Binding("Address").Name("Address").Colspan(3));
        });
        ld.Add().Cells(clsb =>
        {
            clsb.Add().Name("Buttons").Width("100");
        });
    })
    .ItemFormatter("itemFormatter")
    .CssClass("multirow")
)