Efficiently Handle CRUD Actions in Syncfusion ASP.NET MVC DataGrid with Fetch Request
Tags: aspnetmvc, datagrid, development, syncfusion
Published: 2024-05-30 04:32:59

---
title: Efficiently Handle CRUD Actions in Syncfusion ASP.NET MVC DataGrid with Fetch Request
published: true
date: 2024-05-23 13:12:28 UTC
tags: aspnetmvc, datagrid, development, syncfusion
canonical_url: https://www.syncfusion.com/blogs/post/crud-aspdotnet-mvc-grid-using-fetch
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/isx0cvd9nhdhxf1b2l7c.png
---
**TL;DR:** Learn to handle CRUD actions in Syncfusion ASP.NET MVC DataGrid using Fetch requests. This blog covers binding data and performing CRUD actions using Fetch for server-side updates. It includes examples of adding, editing, and deleting records and handling Fetch success and failure events for smooth execution and real-time data consistency.

Fetch is a robust method that is crucial in modern web development. It allows for the asynchronous sending of data to a server for database updates and the retrieval of data from a server without the need to refresh the entire webpage. This makes for a smoother and more efficient user experience.

The Syncfusion [ASP.NET MVC DataGrid](https://www.syncfusion.com/aspnet-mvc-ui-controls/grid "ASP.NET MVC DataGrid"), a feature-rich component designed to handle vast amounts of data, has built-in support for handling CRUD (Create, Read, Update, Delete) operations. These operations are fundamental to any app that involves data manipulation.

However, recognizing our users’ diverse needs, we have also provided an option for users to execute these CRUD operations in the DataGrid using their own Fetch commands. This means that users can interact with their database in a way that aligns with their specific requirements and preferences.

This feature is particularly beneficial as it allows users to seamlessly integrate their server logic with the Syncfusion ASP.NET MVC DataGrid during CRUD operations. As a result, any changes made during these operations can be immediately and accurately reflected in the Grid.

Let’s see how to bind and perform CRUD operations using Fetch request in the ASP.NET MVC DataGrid.

## Render Syncfusion ASP.NET MVC DataGrid

Syncfusion [ASP.NET MVC DataGrid](https://ej2.syncfusion.com/aspnetmvc/documentation/grid/getting-started-mvc "Getting started with ASP.NET MVC DataGrid") is a feature-rich control for displaying data in a tabular format. Its functionalities include data binding, editing, Excel-like filtering, and selection. It also supports exporting data to Excel, CSV, and PDF formats.

Now, let’s see how to render the ASP.NET MVC DataGrid control. Here, we’ve enabled the [paging](https://ej2.syncfusion.com/aspnetmvc/documentation/grid/paging "Paging in ASP.NET MVC DataGrid") and [editing](https://ej2.syncfusion.com/aspnetmvc/documentation/grid/editing/edit "Editing in ASP.NET MVC DataGrid") features for a more interactive user experience. Refer to the following code example.

```js
@Html.EJS().Grid("Grid")
.EditSettings(e => { e.AllowAdding(true).AllowEditing(true).AllowDeleting(true); })
.Columns(col =>{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("130").Add();
    col.Field("EmployeeID").HeaderText("Employee ID").Width("150").Add();
    col.Field("CustomerID").HeaderText("CustomerID").Width("70").Add();
    col.Field("ShipCity").HeaderText("Ship City").Width("70").Add()
})
.AllowPaging(true)
.AllowSorting(true)
.ActionComplete("actionComplete")
.ActionBegin("actionBegin")
.Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })
.Render()
```

Previously, the **DataSource** was not bound to the DataGrid. However, now we will utilize Fetch requests to bind data to the DataGrid. On the server side, the **GetData** method within the **HomeController** contains the grid’s data source. When the button is clicked, a Fetch request is sent to fetch the data from the server and bind it to the DataGrid control.

```js
public class HomeController : Controller
{        
    public ActionResult Getdata()
    {
        IEnumerable DataSource = OrdersDetails.GetAllRecords();
        return Json(DataSource);
    } 

    //Create a model class and define the properties.
    public class OrdersDetails
    {
       public OrdersDetails()
       {

       }
       public OrdersDetails(int OrderID, string CustomerId, int EmployeeId, double Freight, bool Verified, DateTime OrderDate, string ShipCity, string ShipName, string ShipCountry, DateTime ShippedDate, string ShipAddress)
       {
            this.OrderID = OrderID;
            this.CustomerID = CustomerId;
            this.EmployeeID = EmployeeId;
            this.Freight = Freight;
            this.ShipCity = ShipCity;
            this.Verified = Verified;
            this.OrderDate = OrderDate;
            this.ShipName = ShipName;
            this.ShipCountry = ShipCountry;
            this.ShippedDate = ShippedDate;
            this.ShipAddress = ShipAddress;
       }
       //Render data in this method.

       public static List<OrdersDetails> GetAllRecords()
       {
            List<OrdersDetails> order = new List<OrdersDetails>();
            int code = 10000;
            for (int i = 1; i < 10; i++)
            {
                order.Add(new OrdersDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, new DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7, 16), "Kirchgasse 6"));
                order.Add(new OrdersDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new DateTime(1990, 04, 04), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11), "Avda. Azteca 123"));
                order.Add(new OrdersDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new DateTime(1957, 11, 30), "Cholchester", "Frankenversand", "Germany", new DateTime(1996, 10, 7), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
                order.Add(new OrdersDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, new DateTime(1930, 10, 22), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12, 30), "Magazinweg 7"));
                order.Add(new OrdersDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new DateTime(1953, 02, 18), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997, 12, 3), "1029 - 12th Ave. S."));
                code += 5;
            }
            return order;
       }

       public int? OrderID { get; set; }
       public string CustomerID { get; set; }
       public int? EmployeeID { get; set; }
       public double? Freight { get; set; }
       public string ShipCity { get; set; }
       public bool Verified { get; set; }
       public DateTime OrderDate { get; set; }
       public string ShipName { get; set; }
       public string ShipCountry { get; set; }
       public DateTime ShippedDate { get; set; }
       public string ShipAddress { get; set; }
   }    
}
```

## Retrieving data via Fetch request

We can utilize the **dataSource** property to fetch data from an external source using the Fetch requests and bind it to the ASP.NET MVC DataGrid.

In the following code example, we’ve demonstrated how to fetch data from the server using a Fetch request. Upon successful retrieval, we’ll bind the data to the **dataSource** property within the button click event, using the **onSuccess** event of the Fetch request.

```js
<script>
    let button = document.getElementById('btn');
    button.addEventListener("click", function (e) {
        let fetch= new ej2.base.Fetch("/Home/Getdata", "POST");
        fetch.send();
        fetch.onSuccess = function (data) {
            var grid = document.getElementById('Grid').ej2_instances[0];
            grid.dataSource = JSON.parse(data);
        };
    });
</script>
```

## Performing CRUD actions with Fetch requests

In addition to binding data, you can utilize Fetch requests to handle CRUD (Create, Read, Update, Delete) actions and update your data on the server side. When any grid action is performed, the [actionBegin](https://help.syncfusion.com/cr/aspnetmvc-js2/Syncfusion.EJ2.Grids.Grid.html#Syncfusion_EJ2_Grids_Grid_ActionBegin "actionBegin property of the ASP.NET MVC DataGrid") event is triggered before the action occurs in the grid.

By leveraging the actionBegin event, you can cancel the default CRUD operations by utilizing the **cancel** argument provided by this event. This allows you to call your server-side method dynamically using Fetch and the relevant data received from the actionBegin event to update your server data accordingly.

## Adding a new record with Fetch request

To create a new record using Fetch requests, you can follow these steps:

1.Click on the **Add** icon located in the grid’s toolbar. This action will generate a form within the grid, enabling you to input the necessary details.
2.After entering the details, click the **Update** icon in the toolbar to commit the changes.
3.Throughout this process, the **actionBegin** event is activated. In this event, you can retrieve the **requestType** as **save** and the **action** value as **add** from the argument.
4.Armed with this information, you can cancel the default action and send a Fetch request to execute the add action on the server side.

Refer to the following code example.

```js
//Insert the record.
public ActionResult Insert(OrdersDetails value)
{
      OrdersDetails.GetAllRecords().Insert(0, value);
      return Json(value);
}
```

Now, we are going to call the **Insert** method from **actionBegin** event through fetch call.

```js
<script>
    var flag = false;
    function actionBegin(e) {
        // Initially the flag needs to be false in order to enter this condition.
        if (!flag) {
            var grid = document.getElementById('Grid').ej2_instances[0];
            // Add and edit operations.
            if (e.requestType == 'save' && (e.action == 'add')) {
                var editedData = e.data;
                // The default edit operation is canceled.
                e.cancel = true;
                // Here, you can send the updated data to your server using a fetch call.
                var fetch= new ej.base.Fetch({
                    url: '/Home/Insert',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ value: editedData })
                });
                fetch.onSuccess = (args) => {
                    // Flag is enabled to skip this execution when grid ends add/edit action.
                    flag = true;
                    // The added/edited data will be saved in the Grid.
                    grid.endEdit();
                }
                fetch.onFailure = (args) => {
                    // Add/edit failed.
                    // The flag is disabled if the operation fails so that it can enter the condition on the next execution.
                    flag = false;
                }
                fetch.send();
            }
    }
```

In the Fetch success event, you can utilize the Grid’s [endEdit](https://ej2.syncfusion.com/documentation/api/grid/#endedit "endEdit property for the ASP.NET MVC - EJ2 Grid") method for adding and editing and[deleteRecord](https://ej2.syncfusion.com/documentation/api/grid/#deleterecord "deleteRecord method property for the ASP.NET MVC - EJ2") method to delete the corresponding data in the Grid. However, it’s worth noting that invoking these methods trigger the **actionBegin** event again to save the changes in the DataGrid.

To prevent this behavior and control the execution flow, you can employ a flag variable and manage it within the [actionComplete](https://help.syncfusion.com/cr/aspnetmvc-js2/Syncfusion.EJ2.Grids.Grid.html#Syncfusion_EJ2_Grids_Grid_ActionComplete "actionComplete property of the ASP.NET MVC DataGrid") event and Fetch failure events.

Refer to the following code example.

```js
function actionComplete(e) {
   if (e.requestType === 'save' || e.requestType === 'delete') {
      // The flag is disabled after the operation is successfully performed so that it can enter the condition on the next execution.
      flag = false;
   }
}
```

## Updating and saving a record using a Fetch request

To edit and save a record using a Fetch request, follow these steps:

1. Select the desired record in the Grid by clicking or using the **Edit** icon in the toolbar. Alternatively, double-click on a row to initiate the editing process for that specific record.
2. In the edit form, make the necessary modifications to the record’s details.
3. Choose the **Update** icon in the toolbar to save the changes.
4. During this process, the **actionBegin** event is triggered. Within this event, retrieve the **requestType**  and **action**  values from the argument.
5. Check if the **requestType** is **save** and the **action** is **edit**  to identify the specific scenario of editing a record.
6. If the conditions are met, cancel the default action by utilizing the appropriate mechanism provided by your DataGrid library. This ensures that the grid’s default behavior for the edit action is bypassed.
7. Finally, construct a Fetch request to call the update method in the controller.

Refer to the following code example.

```js
//Update the record.
Public ActionResult Update(OrdersDetails value)
{
     var ord = value;
     OrdersDetails val = OrdersDetails.GetAllRecords().Where(or => or.OrderID == ord.OrderID).FirstOrDefault();
     val.OrderID = ord.OrderID;
     val.EmployeeID = ord.EmployeeID;
     val.CustomerID = ord.CustomerID;
     return Json(value);
}
```

Now, we are going to call the **Update** method from the **actionBegin** event through Fetch call.

```js
<script>
    var flag = false;
    function actionBegin(e) {
        // Initially, the flag needs to be false in order to enter this condition.
        if (e.requestType == 'save' && (e.action == 'edit')) {
                var editedData = e.data;
                // The default edit operation is canceled.
                e.cancel = true;
                // Here, you can send the updated data to your server using a Fetch call.
                var fetch= new ej.base.Fetch ({
                    url: '/Home/Update',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ value: editedData })
                });
                fetch.onSuccess = (args) => {
                    // Flag is enabled to skip this execution when the DataGrid ends add/edit action.
                    flag = true;
                    // The added/edited data will be saved in the Grid.
                    grid.endEdit();
                }
                fetch.onFailure = (args) => {
                    // Add/edit failed.
                    // The flag is disabled if operation is failed so that it can enter the condition on next execution.
                    flag = false;
                }
                fetch.send();
            }
    }
```

## Deleting a record using Fetch request

To delete a record using a Fetch request, follow these steps:

1. Select the record you wish to delete in the Grid by clicking on it or using the **Delete** icon in the toolbar.
2. When the record is selected for deletion, the **actionBegin** event is triggered. Within this event, retrieve the **requestType**  value from the argument.
3. Check if the  **requestType** is **delete**  to identify the delete action.
4. If the condition is met, cancel the default action using the appropriate mechanism available in your DataGrid library. This prevents the default behavior of the grid for the delete action.
5. Construct a Fetch request to call the **delete** method in the controller.
6. Configure the Fetch settings, such as the **URL**, **data**, and **success**/**error** handling, based on your specific requirements.

Refer to the following code example.

```js
//Delete the record.
public ActionResult Delete(int key)
{
    OrdersDetails.GetAllRecords().Remove(OrdersDetails.GetAllRecords().Where(or => or.OrderID == key).FirstOrDefault());
    var data = OrdersDetails.GetAllRecords();
    return Json(data);
}
```

Now, we are going to call the **Delete** method from the **actionBegin** event through Fetch call.

```js
<script>
    var flag = false;
    function actionBegin(e) {

        if (e.requestType == 'delete') {
                var editedData = e.data;
                // The default delete operation is canceled.
                e.cancel = true;
                // Here, you can send the deleted data to your server using a Fetch call.
                var fetch= new ej.base.Fetch ({
                    url: '/Home/Delete',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ key: editedData[0][grid.getPrimaryKeyFieldNames()[0]] })
                })
                fetch.onSuccess = (args) => {
                    // Flag is enabled to skip this execution when grid deletes a record.
                    flag = true;
                    // The deleted data will be removed from the Grid.
                    grid.deleteRecord();
                }
                fetch.onFailure = (args) => {
                    // Delete failed.
                    // The flag is disabled if the operation fails so that it can enter the condition on the next execution.
                    flag = false;
                }
                fetch.send();
            }
      }
```

Refer to the following output image.[![Syncfusion DataGrid CRUD with Fetch](https://www.syncfusion.com/blogs/wp-content/uploads/2024/05/Syncfusion-DataGrid-CRUD-with-Fetch.gif)](https://www.syncfusion.com/blogs/wp-content/uploads/2024/05/Syncfusion-DataGrid-CRUD-with-Fetch.gif)

## Conclusion

Thanks for reading! In this blog, we’ve explored how to handle CRUD actions in Syncfusion [ASP.NET MVC DataGrid](https://ej2.syncfusion.com/aspnetmvc/documentation/grid/getting-started-mvc "Getting started with ASP.NET MVC DataGrid") efficiently using Fetch requests. By leveraging Fetch, we can dynamically fetch and update data from the server without the need to refresh the entire page.

The new version of Essential Studio is available for download from the [License and Downloads](https://www.syncfusion.com/account/downloads "Essential Studio License and Downloads page") page for existing customers. If you are not a Syncfusion customer, try our 30-day [free trial](https://www.syncfusion.com/downloads "Get free evaluation of the Essential Studio products") to explore our available features.

You can contact us through our [support forum](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/?_gl=1*1f52z3y*_ga*MTc3NTk2OTU1MC4xNjQ1MjA1MTE2*_ga_WC4JKKPHH0*MTY0ODU1MjUxNi4xMzguMS4xNjQ4NTUyNTM0LjA. "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback "Syncfusion Feedback Portal"). We are here to help you succeed!

## Related blogs

- [Easy Steps to Migrate an ASP.NET MVC Project to an ASP.NET Core Project (syncfusion.com)](https://www.syncfusion.com/blogs/post/migrate-asp-net-mvc-project-to-asp-net-core "Blog: Easy Steps to Migrate an ASP.NET MVC Project to an ASP.NET Core Project (syncfusion.com)")
- [Easy Steps to Use Dropdown Tree with Organization Structures in ASP.NET MVC Applications | Syncfusion Blogs](https://www.syncfusion.com/blogs/post/easy-steps-to-use-dropdown-tree-with-organization-structures-in-asp-net-mvc-applications "Blog: Easy Steps to Use Dropdown Tree with Organization Structures in ASP.NET MVC Applications | Syncfusion Blogs")
- [How to Migrate SQL Server in an ASP.NET MVC Application to MySQL and PostgreSQL | Syncfusion Blogs](https://www.syncfusion.com/blogs/post/how-to-migrate-sql-server-in-an-asp-net-mvc-application-to-mysql-and-postgresql "Blog: How to Migrate SQL Server in an ASP.NET MVC Application to MySQL and PostgreSQL | Syncfusion Blogs")
- [Shield Your ASP.NET MVC Web Applications with Content Security Policy (CSP) (syncfusion.com)](https://www.syncfusion.com/blogs/post/asp-dotnet-mvc-content-security-policy "Blog: Shield Your ASP.NET MVC Web Applications with Content Security Policy (CSP) (syncfusion.com)")