layui学习之路——删除数据表格记录
上一篇写了基本的数据展现,今天写删除记录。
html
把删除按钮放在表格的顶端工具栏位置
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<asp:button class="layui-btn layui-btn-sm" lay-event="delete">删除</asp:button>
</div>
</script>
<table id="demo" lay-filter="test" ></table>
js
$(document).ready(function() {
reloadTable();
});
//加载表格这块和上一篇一样,直接复制过来了
function reloadTable(){ //这里将数据表格封装成一个方法,方便之后添加功能
layui.use(['upload', 'element', 'layer','table'],function(){
var table=layui.table;
//var layer = layui.layer;
//var upload=layui.upload;
var index = layer.load(1); //添加laoding,0-2两种方式
table.render({
elem:'#demo', //对应html的table的id
height:600, //整张表的高度,设置高度后自动锁定表头
url:'global/DataService_Test.ashx' , //数据源,就是下面的文件
loading:false, //加载条
method:'post', //post方法本地第一次加载IE会报error,谷歌没问题
page:false, //分页
// toolbar: '#toolbarDemo', //指向自定义工具栏
defaultToolbar: [],
// limit:20,
request: {
pageName: 'page', //页码的参数名称,默认:page
limitName: 'limit' //每页数据量的参数名,默认:limit
},
id: 'table1',
parseData: function(res) {
return {
"code": res.code, //数据状态的字段名称,默认:code
"msg": res.msg, //成功的状态码,默认:0
"count": res.count, //状态信息的字段名称,默认:msg
"data": res.data//数据总数的字段名称,默认:count
//dataName: 'data' //数据列表的字段名称,默认:data
};
},
cols:[[
{type:'radio'} //单选列
,{field: 'col1', title: 'col1', align:'center'}
,{field: 'col2', title: 'col2',align:'center'}
,{field: 'col3', title: 'col3',width:100, align:'center'}
]],
done: function(res, curr, count) { //返回数据执行回调函数
console.log(res); //所有数据
console.log(curr); //得到当前页码
console.log(count);//得到数据总量
layer.close(index); //返回数据关闭loading
}
});
table.on('toolbar(test)',function(obj){ //删除事件,test为lay-filter的值,记得写在 layui.use(['upload', 'element', 'layer','table'],function()这个里面
var checkStatus = table.checkStatus(obj.config.id);
var data = checkStatus.data; //获取选中的数据
switch(obj.event){
case 'delete':
if (data.length > 0) {
var col1= data[0].col1;
layer.open({
title: '你确定删除' + col1+ '?'
, btn: ['确定', '取消']
, yes: function(index, layero) {
//layer.msg('确定');
var p1 = new Object();
p1.name = "col1";
p1.value = col1;
var array = [];
array.push(p1);
$.ajax({ //给删除模块传递col1参数
url: "global/ActionService.ashx?action=deleteRow",
type: "POST",
cache: false,
dataType: "json",
async: false,
data: JSON.stringify(array),
success: function(result) {
if (result == 1) {
layer.msg('删除成功!');
//layui.table.reload('table1');//这个刷新不知道为什么没用……
// window.location.reload(); //这两个刷新效果差不多
window.parent.location.reload();
}
else {
layer.msg('删除失败!');
return false;
}
},
error: function(result) {
}
});
}
, btn2: function(index, layero) {
layer.close(index);
}
});
} else { layer.msg('请先选择一条数据'); }
break;
}
});
});
} //js的括号真令人头大
两个ashx应该可以合并的,传递数据用action区分
DataService_Test.ashx
public class DataService_Test : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
DataSet ds = new DataSet();
SqlConnection DB = new SqlConnection(WebConfigurationManager.AppSettings["key"].ToString());
string sql_text = @"select col1,col2,col3 from table";
DB.Open();
SqlDataAdapter objAdapter = new SqlDataAdapter(sql_text, DB);
objAdapter.Fill(ds, "data");
context.Response.Write(ToJsonTableRun(ds.Tables["data"])); //输出datatable
DB.Close();
}
public string ToJsonTableRun(DataTable dt) { //datatable数据转化为json格式
JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
JavaScriptSerializer.MaxJsonLength = int.MaxValue;
ArrayList arrayList = new ArrayList();
foreach(object obj in dt.Rows){
DataRow dataRow = (DataRow)obj;
Dictionary<string,object> dictionary=new Dictionary<string,object>();
foreach(object obj2 in dt.Columns){
DataColumn dataColumn = (DataColumn)obj2;
dictionary.Add(dataColumn.ColumnName,dataRow[dataColumn.ColumnName].ToString());
}
arrayList.Add(dictionary);
}
Hashtable tableMap = new Hashtable();
tableMap.Add("code", "0");
tableMap.Add("msg", "");
tableMap.Add("count", arrayList.Count);
tableMap.Add("data", arrayList);
return JavaScriptSerializer.Serialize(tableMap);
}
public bool IsReusable
{
get
{
return false;
}
}
}
ActionService.ashx
public void ProcessRequest(HttpContext context)
{
string action = context.Request["action"].ToString(); //获取进行的动作
SqlConnection DB = new SqlConnection(WebConfigurationManager.AppSettings["key"].ToString());
if (action == "deleteRow") //删除
{
DB.Open();
string json = string.Empty;
using (var reader = new StreamReader(context.Request.InputStream))
{
json = reader.ReadToEnd();
}
string col1= string.Empty;
if (!String.IsNullOrEmpty(json))
{
var paraList = new JavaScriptSerializer().Deserialize<List<Para>>(json); //自己新建一个类
foreach (Para p in paraList)
{
switch (p.name)
{
case "col1": //根据col1进行删除
col1= p.value;
break;
}
}
}
string sql_del = "delete from table where col1='" + col1+ "'";
SqlCommand sqlCommand = new SqlCommand(sql_del, DB);
sqlCommand.ExecuteNonQuery();
DB.Close();
context.Response.Write("1"); //输出1就代表删除成功
}
public class Para
{
public string name { get; set; }
public string value { get; set; }
}
}
这样删除就实现了,但是性能在IE上很不理想,删除会卡好久,谷歌就正常。