Search results

Refresh the data source

You can add/delete the data source records through an external button. To reflect the data source changes in the grid, invoke the refresh method.

To refresh the data source:

Step 1:

Add/delete the data source record by using the following code.

    grid.dataSource.unshift(data); // add a new record.

    grid.dataSource.splice(selectedRow, 1); // delete a record.

Step 2:

Refresh the grid after the data source change by using the refresh method.

    grid.refresh(); // refresh the Grid.
razor
refresh-datasource.cs
@Html.EJS().Button("add").Content("Add").IsPrimary(true).Render()

@Html.EJS().Button("delete").Content("Delete").IsPrimary(true).Render()

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).Render()

<script>
    document.getElementById('add').onclick = () => {
        var grid = document.getElementById("Grid").ej2_instances[0];
        var data = { OrderID: 10247, CustomerID: "ASDFG", Freight: 40.4, OrderDate: new Date(8367642e5), ShipCountry: "Austria" };
        grid.dataSource.unshift(data); // add new record.
        grid.refresh(); // refresh the Grid.
    };

    document.getElementById('delete').onclick = () => {
        var grid = document.getElementById("Grid").ej2_instances[0];
        if (grid.getSelectedRowIndexes().length) {
            var selectedRow = grid.getSelectedRowIndexes()[0];
            grid.dataSource.splice(selectedRow, 1); // delete the selected record.
        } else {
            alert("No records selected for delete operation");
        }
        grid.refresh(); // refresh the Grid.
    };

</script>
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}