世俱杯 2025

使用 Fetch 请求在 Syncfusion ASP.NET MVC 数据网格中高效处理 CRUD 操作

原创|使用教程|编辑:张蓉|2025-05-26 11:22:20.850|阅读 32 次

概述:学习如何使用 Fetch 请求在 Syncfusion ASP.NET MVC 数据网格中处理 CRUD 操作。本博客将介绍如何使用 Fetch 进行数据绑定和执行 CRUD 操作,以实现服务器端更新。文中包含添加、编辑和删除记录的示例,以及处理 Fetch 成功和失败事件的方法,确保操作流畅执行和实时数据一致性。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

相关链接:

学习如何使用 Fetch 请求在 Syncfusion ASP.NET MVC 数据网格中处理 CRUD 操作。本博客将介绍如何使用 Fetch 进行数据绑定和执行 CRUD 操作,以实现服务器端更新。文中包含添加、编辑和删除记录的示例,以及处理 Fetch 成功和失败事件的方法,确保操作流畅执行和实时数据一致性。
Fetch 是现代 Web 开发中的一种强大方法,它允许异步向服务器发送数据以更新数据库,或从服务器检索数据而无需刷新整个网页,从而提供更流畅、高效的用户体验。

Syncfusion ASP.NET MVC 数据网格是一个功能丰富的组件,专为处理大量数据而设计,它内置了对 CRUD(创建、读取、更新、删除)操作的支持。这些操作是任何涉及数据操作的应用程序的基础。

   ASP.NET MVC 试用下载

然而,考虑到用户的多样化需求,我们还提供了一种选项,允许用户使用自己的 Fetch 命令在数据网格中执行这些 CRUD 操作。这意味着用户可以按照自己的特定需求和偏好与数据库进行交互。
此功能特别有用,因为它允许用户在 CRUD 操作期间将服务器逻辑与 Syncfusion ASP.NET MVC 数据网格无缝集成。因此,这些操作期间所做的任何更改都可以立即、准确地反映在网格中。
让我们看看如何在ASP.NET MVC 数据网格中使用 Fetch 请求进行数据绑定和执行 CRUD 操作。

渲染 Syncfusion ASP.NET MVC 数据网

Syncfusion ASP.NET MVC 数据网格是一个功能丰富的控件,用于以表格形式显示数据。其功能包括数据绑定、编辑、类似 Excel 的过滤和选择,还支持将数据导出为 Excel、CSV 和 PDF 格式。
现在,让我们看看如何渲染ASP.NET MVC 数据网格控件。在这里,我们启用了分页和编辑功能,以提供更具交互性的用户体验。请参考以下代码示例。
@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()
以前,数据源未绑定到数据网格。但现在我们将使用 Fetch 请求将数据绑定到数据网格。在服务器端,HomeController 中的 GetData 方法包含网格的数据源。当单击按钮时,会发送一个 Fetch 请求从服务器获取数据,并将其绑定到数据网格控件。
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; }
   }    
}

通过 Fetch 请求检索数据

我们可以利用 dataSource 属性,通过 Fetch 请求从外部源获取数据,并将其绑定到 ASP.NET MVC 数据网格。
在以下代码示例中,我们演示了如何使用 Fetch 请求从服务器获取数据。成功检索后,将利用 Fetch 请求的 onSuccess 事件,在按钮点击事件中将数据绑定到 dataSource 属性。
<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>
通过 Fetch 请求执行 CRUD 操作
除了绑定数据外,您还可以利用 Fetch 请求处理 CRUD(创建、读取、更新、删除)操作,并在服务器端更新数据。当执行任何网格操作时,actionBegin 事件会在网格中操作发生前触发。
通过利用 actionBegin 事件,您可以使用该事件提供的 cancel 参数取消默认的 CRUD 操作。这使您能够使用 Fetch 动态调用服务器端方法,并通过 actionBegin 事件接收的相关数据相应地更新服务器数据。

通过 Fetch 请求添加新记

要使用 Fetch 请求创建新记录,可按以下步骤操作:
1.点击网格工具栏中的 添加 图标。此操作将在网格内生成一个表单,允许您输入必要的详细信息。
2.输入详细信息后,点击工具栏中的 更新 图标提交更改。
3.在此过程中,actionBegin 事件会被激活。在该事件中,您可以从参数中获取 requestType 为 save 、action 值为 add。
4.利用这些信息,您可以取消默认操作并发送 Fetch 请求,以在服务器端执行添加操作。
参考以下代码示例:
//Insert the record.
public ActionResult Insert(OrdersDetails value)
{
      OrdersDetails.GetAllRecords().Insert(0, value);
      return Json(value);
}
现在,我们将通过 fetch 调用从 actionBegin 事件中调用 Insert 方法。
<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();
            }
}
在 Fetch 成功事件中,您可以使用网格的endEdit方法(用于添加和编辑操作)和deleteRecord方法(用于删除网格中的对应数据)。但需要注意的是,调用这些方法会再次触发actionBegin事件,以保存数据网格中的更改。
为避免这种情况并控制执行流程,您可以使用一个标志变量,并在actionComplete事件和 Fetch 失败事件中对其进行管理。
参考以下代码示例:
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;
   }
}

使用 Fetch 请求更新和保存记

要使用 Fetch 请求编辑并保存记录,请按以下步骤操作:
1.通过单击或使用工具栏中的 “编辑” 图标,在网格中选择所需记录。或者,双击某一行以启动对该特定记录的编辑过程。
2.在编辑表单中,对记录的详细信息进行必要的修改。
3.选择工具栏中的 “更新” 图标以保存更改。
4.在此过程中,会触发actionBegin事件。在该事件中,从参数中检索requestType和action值。
5.检查requestType是否为save且action是否为edit,以识别编辑记录的特定场景。
6.如果条件满足,使用数据网格库提供的相应机制取消默认操作。这可确保绕过网格对编辑操作的默认行为。
7.最后,构造一个 Fetch 请求以调用控制器中的更新方法。
参考以下代码示例:
//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);
}
现在,我们将通过 Fetch 调用从 actionBegin 事件中调用 Update 方法。
<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();
            }
    }
使用 Fetch 请求删除记
若要使用 Fetch 请求删除记录,请按以下步骤操作:
1.在网格中通过点击记录或使用工具栏中的删除图标,选择您希望删除的记录。
2.当记录被选中删除时,将触发actionBegin事件。在此事件中,从参数中检索requestType值。
3.检查requestType是否为delete,以识别删除操作。
4.如果满足条件,使用数据网格库中可用的相应机制取消默认操作。这将阻止网格对删除操作执行默认行为。
5.构造一个 Fetch 请求,以调用控制器中的删除方法。
6.根据您的具体需求配置 Fetch 设置,例如 URL、数据以及成功 / 错误处理逻辑。
参考以下代码示例:
//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);
}
现在,我们将通过 Fetch 调用从 actionBegin 事件中调用 Delete 方法。
<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();
            }
      }
请参考以下输出图片:
Syncfusion-DataGrid-CRUD-with-Fetch

结论

感谢阅读!在本篇博客中,我们探讨了如何使用 Fetch 请求高效处理 Syncfusion ASP.NET MVC 数据网格中的 CRUD 操作。通过利用 Fetch,我们能够动态地从服务器获取和更新数据,而无需刷新整个页面。
慧都科技是⼀家⾏业数字化解决⽅案公司,专注于软件、⽯油与⼯业领域,以深⼊的业务理解和⾏业经验,帮助企业实现智能化转型与持续竞争优势。
慧都科技作为 Syncfusion 的中国区合作伙伴,Syncfusion 作为 UI 组件研发领域的领先技术提供商,提供 Essential Studio 等强大工具,助力企业实现高效的应用开发与管理。Essential Studio 包括 1900 多个组件和框架,支持 WinForms 等多个主流开发平台,其组件功能强大,可满足大量数据处理需求。Essential Studio 提供丰富的学习资源,包括视频教程、文档和知识库,帮助开发者快速掌握使用方法

标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@dpuzeg.cn


为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP