EasyUI - DataGrid 组建 - [ 删除,修改 ]

效果:

  

 

html代码:

<div style="padding-top: 50px; width: 800px; margin: 0 auto;">
            <!--使用JS加载方式-->
            <table id="tab"></table>

            <!--按钮--->
            <div id="tb">
                <div style="padding: 5px;">
                    <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add', plain:true," onclick="obj.add();">添加</a>
                    <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit', plain:true," onclick="obj.edit();">修改</a>
                    <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove', plain:true," onclick="obj.remove();">删除</a>
                    <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save', plain:true," style="display: none;" id="save" onclick="obj.save();">保存</a>
                    <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-redo', plain:true," style="display: none;" id="redo" onclick="obj.redo();">取消编辑</a>
                </div>
                <div style="padding-left: 10px; padding-bottom: 10px;">
                    搜索姓名(可以模糊查询):<input id="name" name="name" type="text" class="textbox" style="width: 130px;" />
                    查询时间 从:<input id="time_from" name="time_from" type="text" class="easyui-datebox" style="width: 130px;" />
                    到:<input id="time_to" name="time_to" type="text" class="easyui-datebox" style="width: 130px;" />
                    <a id="search" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'," style="margin-left: 20px; padding: 0 10px 0 10px;" onclick="obj.search();">搜索</a>
                </div>
            </div>
        </div>

 

JS代码:

    <script type="text/javascript">
        //扩展 dateTimeBox
        $.extend($.fn.datagrid.defaults.editors, {
            datetimebox: {
                init: function (container, options) {
                    var input = $('<input type="text">').appendTo(container);
                    options.editable = false;
                    input.datetimebox(options);
                    return input;
                },
                getValue: function (target) {
                    return $(target).datetimebox('getValue');
                },
                setValue: function (target, value) {
                    $(target).datetimebox('setValue', value);
                },
                resize: function (target, width) {
                    $(target).datetimebox('resize', width);
                },
                destroy: function (target) {
                    $(target).datetimebox('destroy');
                },
            }
        });

        $(function () {
            obj = {
                editRow: undefined,//undefined默认为false
                search: function () {
                    $('#tab').datagrid('load', {
                        searchvalue: $.trim($('input[name="name"]').val()),
                        time_from: $('input[name="time_from"]').val(),
                        time_to: $('input[name="time_to"]').val(),
                    });
                },
                add: function () {
                    $('#save,#redo').show();
                    /*
                    //当前页行结尾添加
                    $('#box').datagrid('appendRow', {
                        user : 'bnbbs',
                        email : 'bnbbs@163.com',
                        date : '2014-11-11',
                    });
                    */

                    if (this.editRow == undefined) {
                        //添加一行 
                        $('#tab').datagrid('insertRow', {
                            index: 0,
                            row: {
                                /*
                                user : 'bnbbs',
                                email : 'bnbbs@163.com',
                                date : '2014-11-11',
                                */
                            },
                        });

                        //将第一行设置为可编辑状态
                        $('#tab').datagrid('beginEdit', 0);

                        this.editRow = 0;
                    }
                },
                save: function () {
                    //这两句不应该放这里,应该是保存成功后,再执行
                    //$('#save,#redo').hide();
                    //this.editRow = false;
                    //将第一行设置为结束编辑状态
                    $('#tab').datagrid('endEdit', this.editRow);//保存当前选定行
                },
                redo: function () {
                    $('#save,#redo').hide();
                    this.editRow = undefined;
                    $('#tab').datagrid('rejectChanges');
                },
                edit: function () {
                    var rownumber = $('#tab').datagrid('getSelections');

                    if (rownumber.length == 1) {
                        //如果为false时,可以编辑本行。不可在点击另外的一行。
                        if (this.editRow == undefined) {
                            //获取选中行的索引
                            var index = $('#tab').datagrid('getRowIndex', rownumber[0]);
                            $('#save,#redo').show();
                            $('#tab').datagrid('beginEdit', index);
                            this.editRow = index;//原先是没有值,现在把rowindex的值给obj.editrow
                        }
                    }
                    else {
                        $.messager.alert("提示", "请选择一行!");
                    }
                },
                remove: function () {
                    var delnumber = $('#tab').datagrid('getSelections');
                    if (delnumber.length > 0) {
                        $.messager.confirm("提示", "是否要确定删除!", function (flag) {
                            if (flag) {
                                var ids = [];
                                for (var i = 0; i < delnumber.length; i++) {
                                    ids.push("'" + delnumber[i].id + "'");
                                }

                                //删除
                                $.ajax({
                                    type: 'post',
                                    url: '../ashx/delete.ashx',
                                    data: {
                                        ids: "(" + ids.join(',') + ")",
                                    },
                                    beforeSend: function () {
                                        $('#tab').datagrid('loading');
                                    },
                                    success: function (data) {
                                        if (data == -1) {
                                            $.messager.alert("提示", "删除错误!");
                                        }
                                        else {
                                            $('#tab').datagrid('loaded');
                                            $.messager.show({
                                                title: '提示',
                                                msg: data + '名用户被删除成功!',
                                                timeout: 3000,//2秒钟
                                                showtype: 'fade',//null,slide,fade,show
                                            });
                                            $('#tab').datagrid('load');//重新加载数据
                                            $('#tab').datagrid('unselectAll');//取消所有选中
                                        }
                                    },
                                })
                            }
                        });
                    }
                    else {
                        $.messager.alert("提示", "请选择要删除的行。");
                    }
                },
            };

            //格式化日期输出样式
            $('#time_from, #time_to').datebox({
                formatter: function (date) { return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate(); },
            });

            //Datagrid设置
            $('#tab').datagrid({
                //===================================== 样式 ===============================================//
                width: 800,//宽度
                title: '信息列表',//标题名
                iconCls: 'icon-search',//图标
                //singleSelect: true,//是否单选
                striped: true,//是否开启斑马线
                fitColumns: false,//是否自适应宽度(出现滚动条)
                loadMsg: '正在努力加载,请稍后………………',//显示加载提示信息
                //rownumbers: true,//显示行号
                //showHeader: false,//是否显示行头(标题)
                //showFooter:false,//显示行尾,默认情况下不显示,要在后台使用json数据传递
                //==========================================================================================//


                //============================= 加载数据,要显示的字段 =========================================//
                //要加载的数据
                url: "../Json/datagridjson.ashx",
                //要显示的列
                columns: [[
                    {
                        field: 'id',
                        title: '编号',
                        checkbox: true,
                    },
                    {
                        field: 'name',
                        title: '姓名',
                        width: 100,//所有字段设置成100,起到自动平均分配大小的作用
                        halign: 'center',//仅标题居中

                        //显示数据的时候,格式化数据
                        //formatter: function (value, row, index) {
                        //    return '[ ' + value + ' ]';
                        //},

                        //设置为可以编辑的列,只有这样才能使用编辑
                        editor: {
                            type: 'validatebox',
                            //其中写的使一些验证,像邮箱验证等等
                            options: {
                                required: true,
                            },
                        },
                    },
                    {
                        field: 'sex',
                        title: '性别',
                        width: 100,//所有字段设置成100,起到自动平均分配大小的作用

                        //设置为可以编辑的列,只有这样才能使用编辑
                        editor: {
                            type: 'validatebox',
                            //其中写的使一些验证,像邮箱验证等等
                            options: {
                                required: true,
                            },
                        },
                    },
                    //在字段中使用排序,每点击一次,都会向后台POST要排序的字段和正序还是倒序排列。
                    {
                        field: 'createtime',
                        title: '创建时间',
                        width: 400,//所有字段设置成100,起到自动平均分配大小的作用
                        sortable: true,//允许排序
                    }
                ]],
                //==========================================================================================//


                //===================================== 分页 ===============================================//
                //显示分页控件栏
                pagination: true,
                pageNumber: 1,//初始化的时候在第几页
                pageSize: 10,//,每页显示的条数
                pageList: [10, 15, 20],//每页显示的条数
                //==========================================================================================//


                //===================================== 排序 ===============================================//
                //通过POST传递到后台,然后进行排序。
                sortName: 'createtime',
                sortOrder: 'desc',
                //==========================================================================================//


                //===================================== 按钮 ===============================================//
                toolbar: '#tb',
                //==========================================================================================//


                //===================================== 添加一行 ===============================================//
                //检测是否完成添加
                onAfterEdit: function (rowIndex, rowData, changes) {
                    $('#save,#redo').hide();
                    obj.editRow = undefined;
                    //console.log(rowData);
                    //判断是删除数据还是修改数据
                    var inserted = $('#tab').datagrid('getChanges', 'inserted');
                    var updated = $('#tab').datagrid('getChanges', 'updated');

                    //新增
                    if (inserted.length > 0) {
                        $.ajax({
                            type: 'post',
                            url: '../ashx/insert.ashx',
                            data: {
                                rows: inserted,
                            },
                            beforeSend: function () {
                                $('#tab').datagrid('loading');
                            },
                            success: function (data) {
                                if (data == -1) {
                                    $.messager.alert("提示", "增加信息错误!");
                                }
                                else {
                                    $('#tab').datagrid('loaded');
                                    $.messager.show({
                                        title: '提示',
                                        msg: data + '名增加成功!',
                                        timeout: 3000,//2秒钟
                                        showtype: 'fade',//null,slide,fade,show
                                    });
                                    $('#tab').datagrid('load');//重新加载数据
                                }
                            },
                        })
                    }

                    //修改
                    if (updated.length > 0) {
                        $.ajax({
                            type: 'post',
                            url: '../ashx/update.ashx',
                            data: {
                                rows: updated,
                            },
                            beforeSend: function () {
                                $('#tab').datagrid('loading');
                            },
                            success: function (data) {
                                if (data == -1) {
                                    $.messager.alert("提示", "修改信息错误!");
                                }
                                else {
                                    $('#tab').datagrid('loaded');
                                    $.messager.show({
                                        title: '提示',
                                        msg: data + '修改成功!',
                                        timeout: 3000,//2秒钟
                                        showtype: 'fade',//null,slide,fade,show
                                    });
                                    $('#tab').datagrid('load');//重新加载数据
                                }
                            },
                        })
                    }
                },
                //==========================================================================================//
                //双击一行,进行修改
                onDblClickRow: function (rowIndex, rowData) {
                    //如果为false时,可以编辑本行。不可在点击另外的一行。
                    if (obj.editRow == undefined) {
                        $('#save,#redo').show();
                        $('#tab').datagrid('beginEdit', rowIndex);
                        obj.editRow = rowIndex;//原先是没有值,现在把rowindex的值给obj.editrow
                    }
                }
            });
        })
    </script>

 

后台代码:

datagridjson.ashx:

  • 加载数据,搜索:
public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            //接受前台传递来的页数和每页显示的条数
            //前台开启分页之后,传递来的参数
            int pageIndex = Convert.ToInt32(context.Request["page"]);
            int pagenumber = Convert.ToInt32(context.Request["rows"]);


            //接收排序字段
            string sortfield = context.Request["sort"];
            string sortDescOrasc = context.Request["order"];


            //------------------------------------------搜索-----------------------------------------
            string connect = "";
            string searchvalue = "";
            string time_from = "";
            string time_to = "";

            if (context.Request["searchvalue"] != null && context.Request["searchvalue"] != "")
            {
                searchvalue = "name like '%" + context.Request["searchvalue"] + "%' and ";
                connect += searchvalue;
            }

            if (context.Request["time_from"] != null && context.Request["time_from"] != "")
            {
                time_from = "createtime>='" + context.Request["time_from"].Replace('/','-') + "' and ";
                connect += time_from;
            }

            if (context.Request["time_to"] != null && context.Request["time_to"] != "")
            {
                time_to = "createtime<='" + context.Request["time_to"].Replace('/', '-') + "' and ";
                connect += time_to;
            }

            if (connect != "")
            {
                connect = " where " + connect.Substring(0, connect.Length - 4);
            }
            //--------------------------------------------------------------------------------------------


            //存储数据
            DataTable dt = new DataTable();

            if (pageIndex == 1)
            {
                //加载第一页
                string pageIndexOne = "select top " + pagenumber + " id, name, sex, createtime from Tb_person "+connect+"  order by " + sortfield + " " + sortDescOrasc + "";
                //获取并转换为JSON数据
                dt = SQLHelper.ExecuteTable(pageIndexOne, CommandType.Text);
            }
            else if (pageIndex != 1)
            {
                //加载非第一页
                string pageIndexNotOne = @"select id, name, sex, createtime from (select ROW_NUMBER() over(order by " + sortfield + " " + sortDescOrasc + ") as rownum, id, name, sex, createtime from Tb_person " + connect + " ) as a where a.rownum > " + (pageIndex - 1) * pagenumber + " and a.rownum <= " + pageIndex * pagenumber + "";
                //获取并转换为JSON数据
                dt = SQLHelper.ExecuteTable(pageIndexNotOne, CommandType.Text);
            }
            else { }


            //将datatable转换为json
            //在返回的JSON数据中,加入total属性(总记录数)
            //那么他就会在加载的时候,显示总记录数。
            //显示的格式是【 {"total":12, "rows":"[{},{},{}]"} 】,rows内为JSON数据。
            //计算总条数(同时可以统计,使用关键字查询之后的条数)
            int totalnumber = (int)SQLHelper.ExcuteScalar("select count(*) from Tb_person " + connect + "", CommandType.Text);
            //返回数据
            string strjson = "{\"total\":" + totalnumber + ", \"rows\":" + DatatableToJson.ToJson(dt) + "}";

            context.Response.Write(strjson);
        }

 

 

insert.ashx:

public void ProcessRequest(HttpContext context)
        {
            string name = context.Request["rows[0][name]"];
            string sex = context.Request["rows[0][sex]"];

            int count = 0;
            try
            {
                count = SQLHelper.ExecuteNonQuery("insert into Tb_person (name, sex) values ('" + name + "', '" + sex + "')", CommandType.Text);
                if (count != 0)
                {
                    context.Response.Write(1);
                }
            }
            catch
            {
                context.Response.Write(-1);
            }
        }

 

 

delete.ashx:

public void ProcessRequest(HttpContext context)
        {
            int count = 0;
            string deletevalue = context.Request["ids"];
            try
            {
                count = (int)SQLHelper.ExecuteNonQuery("delete from Tb_person where id in " + deletevalue + "", CommandType.Text);
                if (count > 0)
                {
                    context.Response.Write(count);
                }
            }
            catch
            {
                context.Response.Write(-1);
            }
        }

 

 

update.ashx:

public void ProcessRequest(HttpContext context)
        {
            string id = context.Request["rows[0][id]"];
            string name = context.Request["rows[0][name]"];
            string sex = context.Request["rows[0][sex]"];
            int count = 0;

            try
            {
                count = SQLHelper.ExecuteNonQuery("update Tb_person set name = '"+name+"', sex = '"+sex+"' where id = '"+id+"'", CommandType.Text);
                if (count >0 )
                {
                    context.Response.Write(count);
                }
            }
            catch
            {
                context.Response.Write(-1);
            }
        }

 

posted on 2015-11-02 20:11  ultrastrong  阅读(337)  评论(0编辑  收藏  举报