原創|使用教程|編輯:張蓉|2025-05-26 11:22:20.850|閱讀 135 次
概述:學習如何使用 Fetch 請求在 Syncfusion ASP.NET MVC 數據網格中處理 CRUD 操作。本博客將介紹如何使用 Fetch 進行數據綁定和執行 CRUD 操作,以實現服務器端更新。文中包含添加、編輯和刪除記錄的示例,以及處理 Fetch 成功和失敗事件的方法,確保操作流暢執行和實時數據一致性。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
Syncfusion ASP.NET MVC 數據網格是一個功能豐富的組件,專為處理大量數據而設計,它內置了對 CRUD(創建、讀取、更新、刪除)操作的支持。這些操作是任何涉及數據操作的應用程序的基礎。
然而,考慮到用戶的多樣化需求,我們還提供了一種選項,允許用戶使用自己的 Fetch 命令在數據網格中執行這些 CRUD 操作。這意味著用戶可以按照自己的特定需求和偏好與數據庫進行交互。@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; }
   }    
}
<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 操作//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事件,以保存數據網格中的更改。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;
   }
}
//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 請求刪除記錄//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();
            }
      }
 請參考以下輸出圖片: 
 
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@ke049m.cn