用EasyUI-DataGrid實現列表批量刪除的功能(ASP.NET/MVC)
阿新 • • 發佈:2018-11-09
1、前端程式碼:首先給列表新增多選框。注意:當singleSelect的屬性值為false時,才能實現多選功能;當checkbox屬性值為true選擇行勾選,false選擇行不勾選。
<table id="dataGrid" class="easyui-datagrid" title="" data-options="rownumbers:'true' ,iconCls:'icon-site',nowrap: true, collapsible: true,idField: 'Id',singleSelect:false"> <thead> <tr> <th data-options="field:'cb',checkbox:true"></th> <th data-options="field:'GoodsId',width:'60px',align:'center'">商品編號</th> <th data-options="field:'DisplayName',width:'300px',align:'left'">商品名稱</th> <th data-options="field:'VIPPrice',align:'right',width:'100px',formatter:FormatterMoney,editor:{type:'numberbox',options:{precision:2}}">專櫃價</th> <th data-options="field:'Price',align:'right',width:'100px',formatter:FormatterMoney">原價</th> <th data-options="field:'Level',align:'center',width:'100px'">等級</th> <th data-options="field:'IsEnable',width:'100px', align:'center',formatter:formatTop">是否在售</th> <th data-options="field:'IsWeb',width:'100px', align:'center',formatter:formatTop">是否網站可見</th> </tr> </thead> </table>
效果如下圖所示:
2、JS程式碼:從前端到後臺進行傳值,完成互動。原理:利用getselections屬性,將列表選中行的id迴圈寫入陣列,利用ajax傳送post請求將值傳到Controller,迴圈刪除。
$("#DelBtn").bind("click", function () { var selRow = $("#dataGrid").datagrid("getSelections");//返回選中多行 if (selRow.length == 0) { $.MsgBox.Alert("提示", "請至少選擇一行資料!"); return false; } var ids = []; //定義陣列,用來記錄列表id for (var i = 0; i < selRow.length; i++) { var id = selRow[i].Id; //取列表中的單個Id ids.push(id); } $.MsgBox.Confirm("警告", "確定要刪除選中的商品?", function () {//四個可選引數 $.ajax({ type: "POST", async: false, dataType: "json", url: "/Customer/DeleteGoodsDetails", data: { ids: ids, counterId: $("#counterId").val() }, success: function (result) { if (result==1) { $.MsgBox.Alert("提示", "恭喜您成功刪除選定商品!"); $("#dataGrid").datagrid("reload"); $('#datagrid').datagrid('clearSelections'); //這行程式碼很重要 } else { $.MsgBox.Alert("提示", "刪除失敗,請重新操作!"); return; } } }); }, function () { return false; }); });
注意:最開始筆者沒寫下面這行程式碼:$('#datagrid').datagrid('clearSelections');
於是出現如下bug:當使用批量刪除列表中勾選的資料,當再次進行批量刪除的操作時,在跟蹤除錯程式碼的時候會發現前一次刪除的記錄會一起傳到後臺,只有重現載入頁面才能進行正常刪除。後來發現,進行選中多行資料提交併刪除後,getSelections屬性會記錄了id的快取,因此需要在刪除後將其釋放。
解決辦法:
$('#datagrid').datagrid('clearSelections'); //或者selRow.length=0;
3、Controller作為資料傳輸紐帶,在底層實現批量刪除。(PS:程式碼中一些封裝的方法因不同的專案而異,)
public int DeleteCounterDetail(List<int> ids, int counterId)
{
foreach (var id in ids)
{
BaseManage<VIPCounterDetail> bm = new BaseManage<VIPCounterDetail>();
QueryOption<VIPCounterDetail> opt = new QueryOption<VIPCounterDetail>();
opt.Conditions.Add(new QueryConditionExt<VIPCounterDetail>() { FieldExp = p => p.Id, SymbolEnum = QueryConditionSymbol.Equals, Val = id });
IList<VIPCounterDetail> list = bm.Query(opt).Items;
if (bm.Remove(list[0].Id) == 1)
{
UpdateInfo(counterId, "del");
}
}
return 1;
}