原创|使用教程|编辑:张蓉|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