【LayUI】动态数据表格+分页+CheckBox
功能描述:
使用layui动态生成带有复选框的table,初始化打开时回显复选框选中项;翻页时记录勾选的数据;
效果展示:
加入资源包页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddSourceToResourcePack.aspx.cs" Inherits="Ruby.Admin.MarketingManage.AddSourceToResourcePack" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>加入资源包设置</title> <script src="../../new_website/scripts/jquery1.8.3/jquery-1.8.3.min.js" type="text/javascript"></script> <link href="../../new_website/scripts/layui/css/layui.css" rel="stylesheet" /> <script src="../../new_website/scripts/layui/layui.all.js" type="text/javascript"></script> <script src="../../new_website/scripts/vue/vue.min.js"></script> </head> <body> <div id="data_view" style="margin: 10px"> <div style="margin-top: 10px;"> <form id="form1" runat="server" lay-filter="FormData" class="layui-form"> <div class="layui-form-item"> <div class="layui-inline"> <div class="layui-input-inline"> <asp:TextBox ID="txtResourceNo" runat="server" CssClass="layui-input" placeholder="资源包号"></asp:TextBox> </div> </div> <div class="layui-inline"> <div class="layui-input-inline"> <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="btnSelect">搜索</button> </div> </div> </div> </form> </div> <div id="divResourcePackList"> <p style="margin-bottom: 5px">共计资源包<span id="packCount" style="color: blue">0</span>个,已选<span id="checkedCount" style="color: red">0</span>个</p> <table id="tbResourcePack" lay-filter="tbResourcePack"></table> <div style="float: right; margin: 10px 0px"> <button id="btnAddGoods" type="button" class="layui-btn layui-btn-normal" v-on:click="doSave()">确 定</button> <button type="button" class="layui-btn layui-btn-primary" v-on:click="doCancel()">取 消</button> </div> </div> </div> <script> var data_view = new Vue({ el: '#data_view', data: { storeBrandID: '', MenuTag: '', //菜单标识,store 门店 SourceID: '', SourceName: '', SourceStatus: '', ModularType: '', loginer: '', CheckedArray: [], //记录选中行数据 layTable: '', pageSize: '10', }, mounted: function () { var that = this; //初始化变量 that.storeBrandID = '<%= BrandID %>', that.MenuTag = '<%= MenuTag %>'; that.SourceID = '<%= SourceID %>'; that.SourceName = '<%= SourceName %>', that.SourceStatus = '<%= SourceStatus %>', that.ModularType = '<%= ModularType %>'; that.loginer = '<%= Session["operName"]%>', layui.use(['form', 'laypage', 'table'], function () { var form = layui.form; //查询按钮 form.on('submit(btnSelect)', function (formData) { that.GetResourcePackList(formData.field, 1, that.pageSize) return false; }); form.render(); //初始化加载列表 that.GetResourcePackList(form.val("FormData"), 1, that.pageSize) that.CheckedResourcePack(); }) }, methods: { //获取已经加入到资源包的信息,回显使用 CheckedResourcePack: function () { var that = this; if (that.MenuTag == 'store') { var params = { storeBrandID: that.storeBrandID, flag: "CheckedResourcePack" }; $.ajax({ type: "post", dataType: "json", url: '../handle/Store.ashx', data: params, async: false, success: function (result) { //console.log(result) that.CheckedArray = []; if (result.data.length > 0) { for (var i = 0; i < result.data.length; i++) { that.CheckedArray.push(result.data[i].ResourcePackNo) } } } }); } else { var params = { SourceID: that.SourceID, SourceName: that.SourceName, ModularType: that.ModularType, MenuTag: that.MenuTag, flag: "CheckedResourcePack" }; $.ajax({ type: "post", dataType: "json", url: '../handle/Marketing.ashx', data: params, async: false, success: function (result) { //console.log(result) that.CheckedArray = []; if (result.data.length > 0) { for (var i = 0; i < result.data.length; i++) { that.CheckedArray.push(result.data[i].ResourcePackNo) } } } }); } }, //获取所有资源包信息列表 GetResourcePackList: function (paramsdata, pageIndex, pageSize) { var that = this; var params = { ResourceNo: paramsdata.txtResourceNo, flag: 'GetResourcePackList' } layTable = layui.table; var dataArr = [];//当前页面数据 layTable.render({ id: 'tbResourcePack', elem: '#tbResourcePack', //指定原始表格元素选择器(推荐id选择器) page: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], limit: 10, cols: [[ //标题栏,设置表头 { checkbox: true, title: '全选' } , { field: 'ID', width: 80, title: 'ID' } , { field: 'ResourcePackNo', width: 120, title: '资源包编号' } , { field: 'Name', width: 150, title: '资源包名称' } , { field: 'Describe', title: '备注说明' } ]], method: 'post', url: '../handle/Store.ashx', contentType: 'application/x-www-form-urlencoded', where: params, request: { pageName: 'pageIndex', //页码的参数名称,默认:page limitName: 'pageSize' //每页数据量的参数名,默认:limit }, parseData: function (res) { //console.log(res) dataArr = res.data return { "code": '0', //解析接口状态 "msg": res.message, //解析提示文本 "count": res.result, //解析数据长度 "data": res.data //解析数据列表 }; }, done: function (res) { //console.log(res) //console.log(that.CheckedArray) document.getElementById('packCount').innerHTML = res.count; //资源包总数 document.getElementById('checkedCount').innerHTML = that.CheckedArray.length; //选中数量(回显) var data = res.data; //资源包列表数据 var num = 0; for (var i = 0; i < data.length; i++) { for (var j = 0; j < that.CheckedArray.length; j++) { if (data[i].ResourcePackNo == that.CheckedArray[j]) { num++; data[i]["LAY_CHECKED"] = 'true'; //真正的有效勾选,只有改变LAY_CHECKED的值, table.checkStatus才能抓取到选中的状态 var index = data[i]['LAY_TABLE_INDEX']; $('#divResourcePackList tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true); $('#divResourcePackList tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked'); } } } var limits = $(".layui-laypage-limits").find("option:selected").val(); //每页条数的选择项,值务必对应 limit 参数 //"全选"框被勾选 if ((num == limits || num == res.count) && res.count > 0) { $('#divResourcePackList .layui-table-header table.layui-table thead th input[type="checkbox"]').prop('checked', true); $('#divResourcePackList .layui-table-header table.layui-table thead th input[type="checkbox"]').next().addClass('layui-form-checked'); } } }); //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组 layTable.on('checkbox(tbResourcePack)', function (obj) { if (obj.checked == true) { if (obj.type == 'one') { that.CheckedArray.push(obj.data.ResourcePackNo); } else { for (var i = 0; i < dataArr.length; i++) { that.CheckedArray.push(dataArr[i].ResourcePackNo); } //去重 var array = []; for (var i = 0; i < that.CheckedArray.length; i++) { if (array.indexOf(that.CheckedArray[i]) === -1) { array.push(that.CheckedArray[i]) } } that.CheckedArray = array; } } else { if (obj.type == 'one') { for (var i = 0; i < that.CheckedArray.length; i++) { if (that.CheckedArray[i] == obj.data.ResourcePackNo) { that.removeByValue(that.CheckedArray, that.CheckedArray[i]);//调用自定义的根据值移除函数 } } } else { //for (var i = 0; i < that.CheckedArray.length; i++) { for (var i = that.CheckedArray.length - 1; i > -1; i--) { //for (var j = 0; j < dataArr.length; j++) { for (var j = dataArr.length - 1; j > -1; j--) { if (that.CheckedArray[i] == dataArr[j].ResourcePackNo) { that.removeByValue(that.CheckedArray, that.CheckedArray[i]);//调用自定义的根据值移除函数 //i = i - 1; //splice删除后会更改原数组下标所代表的值 } } } } } document.getElementById('checkedCount').innerHTML = that.CheckedArray.length; //选中数量 //console.log(that.CheckedArray) }); }, doSave: function () { var that = this; if (that.MenuTag == 'store') { that.StoreToResourcePack(); } else { that.SaveToResourcePack(); } }, //自定义方法,根据值去移除 removeByValue: function (arr, val) { for (var i = 0; i < arr.length; i++) { if (arr[i] == val) { arr.splice(i, 1); break; } } }, //取消 doCancel: function () { var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引 parent.layer.close(index); }, //门店信息加入资源包 StoreToResourcePack: function () { var that = this; var storeIds = ""; var param = { brandID: that.storeBrandID, flag: 'GetCakeStoreID' } $.ajax({ type: "post", dataType: "json", url: '../handle/Store.ashx', data: param, async: false, success: function (data) { //console.log(data) var storeIdList = data.data; if (storeIdList.length > 0) { var strStoreIds = ""; for (var i = 0; i < storeIdList.length; i++) { strStoreIds += storeIdList[i].ID + ","; } storeIds = strStoreIds.substring(0, strStoreIds.length - 1); //var checkStatus = layTable.checkStatus('tbResourcePack'); var storeParams = { storeBrandID: that.storeBrandID, storeIds: storeIds, //checkData: JSON.stringify(checkStatus.data), //选中行数据 checkedResourceNo: JSON.stringify(that.CheckedArray), //选中行数据:ResourceNo loginer: that.loginer, flag: 'AddStoreToResourcePack' } $.ajax({ type: "post", dataType: "json", url: '../handle/Store.ashx', data: storeParams, async: false, cache: false, success: function (data) { //console.log(data) if (data.result == "0") { layer.alert('操作成功', { icon: 1, title: '提示', closeBtn: 0, yes: function () { window.parent.location.reload(); } }); } else { layer.alert('操作失败', { icon: 2, title: '提示', closeBtn: 0 }); } } }); } } }); }, //加入资源包 SaveToResourcePack: function () { var that = this; var params = { SourceID: that.SourceID, SourceName: that.SourceName, SourceStatus: that.SourceStatus, ModularType: that.ModularType, MenuTag: that.MenuTag, checkedResourceNo: JSON.stringify(that.CheckedArray), //选中行数据:ResourceNo loginer: that.loginer, flag: 'SaveToResourcePack' } $.ajax({ type: "post", dataType: "json", url: '../handle/Marketing.ashx', data: params, async: false, cache: false, success: function (data) { //console.log(data) if (data.result == "0") { layer.alert('操作成功', { icon: 1, title: '提示', closeBtn: 0, yes: function () { window.parent.location.reload(); } }); } else { layer.alert('操作失败', { icon: 2, title: '提示', closeBtn: 0 }); } } }); }, } }) </script> </body> </html>
保存复选框勾选数据时,添加新勾选的数据,删除取消勾选的数据
public static bool UpdateHotProducts(string ModularType, List<string> newGoodsId)
{
try
{
List<string> sqlList = new List<string>();
DataTable tableGoods = GetHotProductList(ModularType, "", "", 0, 0); //原热门推荐商品列表
List<string> goodsId = new List<string>();
string flName = GetFloorName(ModularType);
if (tableGoods != null && tableGoods.Rows.Count > 0)
{
foreach (DataRow item in tableGoods.Rows)
{
goodsId.Add(item["GoodsID"].ToString()); //添加原商品id
}
}
foreach (var newItem in newGoodsId)
{
//保存的勾选中的热门推荐商品中有,原热门推荐商品列表没有就新增
if (!goodsId.Contains(newItem))
{
sqlList.Add(string.Format(@" insert into dbo.GoodProduct ( GoodsId, CreateTime, DeleteStatus, Sort, ModularType, ModularName )
values ('{0}', getdate(), 0, 0, '{1}', '{2}') ", newItem, ModularType, flName));
}
}
foreach (var item in goodsId)
{
//原热门推荐商品有,保存的勾选中的热门推荐商品没有就删除
if (!newGoodsId.Contains(item))
{
//删除取消勾选的热门推荐商品
sqlList.Add(string.Format(@" delete dbo.GoodProduct where GoodsID='{0}' and ModularType='{1}' ", item, ModularType));
}
}
Ruby_DAL.DbHelperSQL.ExecuteSqlTran(sqlList);
return true;
}
catch (Exception ex)
{
Ruby_Common.LogRecord.WriteLog.WriteLog_Info("Info", new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().ReflectedType.Name, new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name, "设置热门推荐商品出现错误,错误信息:" + ex.Message);
return false;
}
}