Editing in ASP.NET MVC Grid Component

13 May 20229 minutes to read

The Grid component has options to dynamically insert, delete and update records. Editing feature requires a primary key column for CRUD operations. To define the primary key, set IsPrimaryKey property of Column to true in particular column.

You can start the edit action either by double clicking the particular row or by selecting the required row and click on Edit button in the toolbar. Similarly, you can add a new record to grid either by clicking on Add button in the toolbar or on an external button which is bound to invoke the addRecord method of the grid, Save and Cancel while in edit mode is possible using respective toolbar icon in grid.

Deletion of the record is possible by selecting the required row and click on Delete button in the toolbar.

@Html.EJS().Grid("NormalEdit").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = "true", minLength=3 }).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

If IsIdentity is enabled, then it will be considered as a read-only column when editing and adding a record.
You can disable editing for a particular column, by specifying AllowEditing to false.

Toolbar with edit option

The grid toolbar has the built-in items to execute Editing actions. You can define this by using the Toolbar property.

@Html.EJS().Grid("EditToolbar").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).ValidationRules(new { required = "true"}).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = "true", minLength = 3 }).Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Disable editing for particular column

You can disable editing for particular columns by using the AllowEditing property of Column.

In the following demo, editing is disabled for the CustomerID column.

@Html.EJS().Grid("InlineEditing").DataSource((IEnumerable<object>)ViewBag.datasource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).ValidationRules(new { required = "true"}).Add();
    col.Field("CustomerID").HeaderText("Customer Name").AllowEditing(false).Width("150").ValidationRules(new { required = "true", minLength = 3 }).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
public IActionResult Index()
 {
   var orders = OrderDetails.GetAllRecords();
   ViewBag.datasource = orders;            
   return View();
 }

Disable editing for a particular row or cell

You can disable the editing for a particular row by using the ActionBegin event of Grid.

In the below demo, the rows which are having the value for ShipCountry column as Denmark is prevented from editing.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowPaging().Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(30).Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width(30).Add();
    col.Field("ShipCity").HeaderText("Ship City").Width(30).Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width(30).Add();

}).EditSettings(edit => edit.AllowEditing(true)).Toolbar(new List<string>() { "Edit", "Cancel", "Update" }).ActionBegin("actionBegin").Render()

<script>
    function actionBegin(args) {
        if (args.requestType === "beginEdit") {
            if (args.rowData.ShipCountry == "Denmark") {
                args.cancel = true;
            }
        }
    }
</script>
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}

For batch mode of editing, you can use CellEdit event of Grid. In the below demo, the cells which are having the value as Denmark is prevented from editing.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowPaging().Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(30).Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width(30).Add();
    col.Field("ShipCity").HeaderText("Ship City").Width(30).Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width(30).Add();

}).EditSettings(edit => edit.AllowEditing(true).Mode(Syncfusion.EJ2.Grids.EditMode.Batch)).Toolbar(new List<string>() { "Edit", "Cancel", "Update" }).CellEdit("cellEdit").Render()

<script>
    function cellEdit(args) {
        if (args.value == "Denmark") {
            args.cancel = true;
        }
    }
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Editing template column

You can edit the template column value by defining the Field for that particular column.

In the below demo, the ShipCountry column is rendered with the template.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Template("#template").EditType("dropdownedit").Add();

}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()

<script id="template" type="text/x-template">
    <a href="#">${ShipCountry}</a>
</script>
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}

Troubleshoot editing works only for first row

The Editing functionalities can be performed based upon the primary key value of the selected row. If IsPrimaryKey is not defined in the grid, then edit or delete action take places the first row.

How to make a Grid column always editable

Make the Grid column always editable using the column template feature of the Grid.

In the following example, the textbox is rendered in the Freight column using a column template. The keyup event for the Grid is bound using the created event of the Grid, and the edited changes are saved in the data source using the updateRow method of the Grid.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Created("created").Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).IsPrimaryKey(true).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
    col.Field("Freight").HeaderText("Receipt Amount").Width("120").Template("#template").Add();

}).Render()


<script id="template" type="text/x-template">
    <input id='${OrderID}' value='${Freight}' class='custemp' type='text' style='width: 100%'>
</script>

<script>
    function created(e) {
        document.getElementById('Grid').ej2_instances[0].element.addEventListener('keyup', function (e) { // Bind the keyup event for the grid.
            if (e.target.classList.contains('custemp')) { // Based on this condition, you can find whether the target is an input element or not.
                var row = parentsUntil(e.target, 'e-row');
                var rowIndex = row.rowIndex; // Get the row index.
                var uid = row.getAttribute('data-uid');
                var rowData = document.getElementById('Grid').ej2_instances[0].getRowObjectFromUID(uid).data; // Get the row data.
                rowData.Freight = e.target.value; // Update the new value for the corresponding column.
                document.getElementById('Grid').ej2_instances[0].updateRow(rowIndex, rowData); // Update the modified value in the row data.
            }
        });
    }
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

See Also