Features

Batch Editing

Batch Editing

This sample shows the Batch update mode for updating the MultiRow data to server.

Features

Description

The MultiRow control has built-in support for Excel-like, fast, in-cell editing.
Users can begin editing by simply typing into any cell (quick-edit mode), or by pressing F2 or clicking a cell twice (full-edit mode).
There is no need to add extra columns with 'Edit' buttons that switch between display and edit modes.

There are two modes for updating data to server.

Normal Mode

In this mode, which is the default mode, the item updated or created gets committed to the server once the corresponding row finishes editing.
The removed row will be committed to the server immediately.

If user wants to update the data, the Update action Url should be provided. If one wants to add or remove the data, the Create or the Delete action Url should be provided.
And the user should edit the data in the corresponding action.

Batch Mode

In this mode user can update, create or remove multiple items and commit all the changes to the data source once.
The user can commit multiple modifications by sorting, paging or filtering the grid data or simply on a button-click.

The BatchEditing action Url should be provided in this mode.

Note: To disable data update during sort/filter/page operations, set the DisableServerRead property of MultiRow's ItemSource to True.
This will enable client-side sorting, filtering, paging and data will only be submitted when the collectionView's commit method is explicitly called from the client-side.

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

namespace MultiRowExplorer.Controllers
{
    public partial class MultiRowController : Controller
    {
        //
        // GET: /BatchEditing/

        public ActionResult BatchEditing(CollectionViewRequest<Supplier> requestData)
        {
            return View(db.Suppliers.ToList());
        }

        public ActionResult MultiRowBatchEdit([C1JsonRequest]CollectionViewBatchEditRequest<Supplier> requestData)
        {
            return this.C1Json(CollectionViewHelper.BatchEdit(requestData, batchData =>
            {
                var itemresults = new List<CollectionViewItemResult<Supplier>>();
                string error = string.Empty;
                bool success = true;
                try
                {
                    if (batchData.ItemsCreated != null)
                    {
                        batchData.ItemsCreated.ToList().ForEach(st =>
                        {
                            db.Suppliers.Add(st);
                            itemresults.Add(new CollectionViewItemResult<Supplier>
                            {
                                Error = "",
                                Success = ModelState.IsValid,
                                Data = st
                            });
                        });
                    }
                    if (batchData.ItemsDeleted != null)
                    {
                        batchData.ItemsDeleted.ToList().ForEach(supplier =>
                        {
                            var fSupplier = db.Suppliers.Find(supplier.SupplierID);
                            db.Suppliers.Remove(fSupplier);
                            itemresults.Add(new CollectionViewItemResult<Supplier>
                            {
                                Error = "",
                                Success = ModelState.IsValid,
                                Data = supplier
                            });
                        });
                    }
                    if (batchData.ItemsUpdated != null)
                    {
                        batchData.ItemsUpdated.ToList().ForEach(supplier =>
                        {
                            db.Entry(supplier).State = EntityState.Modified;
                            itemresults.Add(new CollectionViewItemResult<Supplier>
                            {
                                Error = "",
                                Success = ModelState.IsValid,
                                Data = supplier
                            });
                        });
                    }
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    var errorList = e.EntityValidationErrors.SelectMany(i => i.ValidationErrors).Select(i => i.ErrorMessage).ToList();

                    try
                    {
                        var refreshableObjects = db.ChangeTracker.Entries().Where(c => c.State == EntityState.Modified).ToList();
                        refreshableObjects.ForEach(o => o.Reload());
                    }
                    catch (Exception er)
                    {
                        errorList.Add(er.Message);
                    }

                    error = string.Join(",", errorList);
                    success = false;
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }

                return new CollectionViewResponse<Supplier>
                {
                    Error = error,
                    Success = success,
                    OperatedItemResults = itemresults
                };
            }, () => db.Suppliers.ToList()));
        }
    }
}
@model IEnumerable<Supplier>

@section Styles{
    <style>
        .queryErrorMessage {
            color: #f00;
        }
    </style>
}

@section Scripts{
    <script type="text/javascript">
        function batchUpdate() {
            var batchEditMultiRow = wijmo.Control.getControl('#batchEditMultiRow'),
                cv = batchEditMultiRow.collectionView;
            cv.commit();

            var isChanged = (cv.itemsAdded && cv.itemsAdded.length)
                || (cv.itemsRemoved && cv.itemsRemoved.length)
                || (cv.itemsEdited && cv.itemsEdited.length);
            if (isChanged) {
                setQueryMessage('@Resources.MultiRowExplorer.BatchEditing_Text11');
            } else {
                setQueryMessage('@Resources.MultiRowExplorer.BatchEditing_Text12');
            }

        }

        function onQueryComplete(sender, e) {
            if (e.result.success) {
                setQueryMessage('@Resources.MultiRowExplorer.BatchEditing_Text13');
            } else {
                setQueryMessage(e.result.error, 'queryErrorMessage');
            }
        }

        function setQueryMessage(message, className) {
            var element = document.getElementById('queryMessage');
            element.innerHTML = message;
            element.className = className;
        }
    </script>
}

<input type="button" value="@Resources.MultiRowExplorer.BatchEditing_Text10" class="btn" onclick="batchUpdate()" />
<span id="queryMessage"></span>
@(
    Html.C1().MultiRow<Supplier>()
        .Id("batchEditMultiRow")
        .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.DisableServerRead(true).Bind(Model).BatchEdit(Url.Action("MultiRowBatchEdit")).OnClientQueryComplete("onQueryComplete"))
        .AllowAddNew(true)
        .AllowDelete(true)
        .CssClass("multirow")
)

@section Summary{
    @Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text9)
}

@section Description{
    <p>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text0)</p>

    <p>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text1)</p>
    <h4>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text7)</h4>
    <p>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text2)</p>

    <p>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text3)</p>

    <h4>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text8)</h4>
    <p>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text4)</p>

    <p>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text5)</p>
    <p>@Html.Raw(Resources.MultiRowExplorer.BatchEditing_Text6)</p>

}