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, 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 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 and editing features for a more interactive user experience. Refer to the following code example.
@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.
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.
<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 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.
//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.
<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 method for adding and editing anddeleteRecord 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 event and Fetch failure events.
Refer to the following code example.
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:
- 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.
- In the edit form, make the necessary modifications to the record’s details.
- Choose the Update icon in the toolbar to save the changes.
- During this process, the actionBegin event is triggered. Within this event, retrieve the requestType and action values from the argument.
- Check if the requestType is save and the action is edit to identify the specific scenario of editing a record.
- 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.
- Finally, construct a Fetch request to call the update method in the controller.
Refer to the following code example.
//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.
<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:
- Select the record you wish to delete in the Grid by clicking on it or using the Delete icon in the toolbar.
- When the record is selected for deletion, the actionBegin event is triggered. Within this event, retrieve the requestType value from the argument.
- Check if the requestType is delete to identify the delete action.
- 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.
- Construct a Fetch request to call the delete method in the controller.
- Configure the Fetch settings, such as the URL, data, and success/error handling, based on your specific requirements.
Refer to the following code example.
//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.
<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.
Conclusion
Thanks for reading! In this blog, we’ve explored how to handle CRUD actions in Syncfusion 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 page for existing customers. If you are not a Syncfusion customer, try our 30-day free trial to explore our available features.
You can contact us through our support forum, support portal, or 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)
- 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
- Shield Your ASP.NET MVC Web Applications with Content Security Policy (CSP) (syncfusion.com)