easyui datagrid 增刪改查

前臺顯示頁面:grid.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="easyui/css/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <link href="easyui/css/themes/icon.css" rel="stylesheet" type="text/css" />
    <link href="easyui/css/demo.css" rel="stylesheet" type="text/css" />
    <link href="easyui/css/dlg.css" rel="stylesheet" type="text/css" />
    <script src="easyui/js/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="easyui/js/jquery.easyui.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#tab").datagrid({
                title: "學生信息",
                iconCls: "icon-save",
                width: 600,
                height: 300,
                collapsible: true,
                autoRowHeight: true,
                striped: true,
                queryParams: { "action": "query" },
                url: "grid.ashx",
                frozenColumns: [[{ field: "chk", "checkbox": true}]],
                columns: [[
                    { field: 'JSON_no', title: "編號", width: 80 },
                    { field: 'JSON_name', title: "姓名", width: 100 },
                    { field: 'JSON_pwd', title: "密碼", width: 100 },
                    { field: 'JSON_sex', title: "性別", width: 100 },
                    { field: 'JSON_age', title: "年齡", width: 100 },
                    { field: 'JSON_address', title: "住址", width: 100 },
                    ]],
                //                toolbar:"#tool",
                toolbar:[{
id:'btnadd',
text:'添加',
iconCls:'icon-add',
handler:function(){
$('#btnsave').linkbutton('enable');
add_dg();
}
},{
id:'btnedit',
text:'編輯',
iconCls:'icon-edit',
handler:function(){
$('#btnsave').linkbutton('enable');
edit_dg();
}
},{
id:'btncut',
text:'刪除',
iconCls:'icon-no',
handler:function(){
$('#btnsave').linkbutton('enable');
dele_dg();
}
}],
                pagination: true,
                rownumbers: true,
                singleSelect:true
            });
            //////////////分頁//////////////////
            $("#tab").datagrid('getPager').pagination({
                beforePageText: '當前第',
                afterPageText: '頁,共{pages}頁',
                displayMsg: ' 當前顯示{from} - {to} 條記錄  共 {total}條記錄',
                pagesize: 10, //頁面大小
                pageList:[10,15,20,30]
            });
        })
        //////////////////////刪除/////////////////
        function dele_dg() {
            //**********返回選中的複選框,返回值是數組(object類型)
            var checked = $("#tab").datagrid('getChecked');
            if (checked[0] != null) {
                var v = '';
                for (var i = 0; i < checked.length; i++) {
                    v += checked[i].JSON_id + ',';
                }
                //************所有選中記錄的id和','組成的字符串
                var str = v.substring(0, v.length - 1);                  
                $.post("grid.ashx", {"action":"del", id: str }, function (data) {
                    $.messager.alert('提示', data, 'info', function () { $("#tab").datagrid("reload"); });
                });
            }
        }
        ////////////////////////////添加///////////////////
        function add_dg() {
            //*********************$('#fm')[0](轉化爲dom對象)先重置表單以免編輯功能的影響
            $('#fm_dg')[0].reset();                   
            $('#dd_dg').show();
            $('#dd_dg').dialog({
                title: '記錄修改',
                width: 400,
                height: 200,
                closed: false,
                cache: false,
                modal: true,
                buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function () {
                        var param = $("#fm_dg").serialize();
                        //解決中文亂碼的
                       var params = decodeURIComponent(param, true);
                       $.post("grid.ashx", { "action": "add", data: params }, function (data) {
                           if (data == 'ok') {
                               $.messager.show({
                                   title: 'success',
                                   msg: '插入成功!'
                               });
                               $('#tab').datagrid('reload');
                           } else {
                               $.messager.show({
                                   title: 'Error',
                                   msg: '插入失敗!'
                               });
                           }
                           $('#tab').datagrid('reload');
                            $('#dd_dg').window('close');
                        });
                    }
                }, {
                    text: '關閉',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        $('#dd_dg').window('close');
                    }
                }]
            });
        }
        /////////////////////////////修改//////////////////////////
        function edit_dg() {
            var selected = $('#tab').datagrid('getSelected');
            if (selected != null) {
                $('#dd_dg').show();
                //***********將表格中選中的一條記錄值傳到編輯窗口
                $('#id').val(selected.JSON_id);
                $("#no").val(selected.JSON_no);
                $('#name').val(selected.JSON_name);
                $('#pwd').val(selected.JSON_pwd);
                //顯示下拉框的選中項
                if (selected.JSON_sex == "男") {
                    $("#sex").find("option").eq(0).attr("selected", "selected");
                } else {
                    $("#sex").find("option").eq(1).attr("selected", "selected");
                }
                $('#age').val(selected.JSON_age);
                $('#address').val(selected.JSON_address);
                $('#dd_dg').dialog({
                    title: '記錄修改',
                    width: 400,
                    height: 200,
                    closed: false,
                    cache: false,
                    modal: true,//顯示遮罩層
                    buttons: [{
                        text: '保存',
                        iconCls: 'icon-save',
                        handler: function () {
                            var param = $("#fm_dg").serialize();
                            var params = decodeURIComponent(param, true);
                            $.post("grid.ashx", { "action":"edit",data:params}, function (data) {
                                if (data == 'ok') {
                                    $.messager.show({
                                        title: 'success',
                                        msg: '修改成功!'
                                    });
                                    $('#tab').datagrid('reload');
                                } else {
                                    $.messager.show({
                                        title: 'Error',
                                        msg: '修改失敗!'
                                    });
                                }
                                $('#dg').datagrid('reload');
                                $('#dd_dg').window('close');
                            });
                        }
                    }, {
                        text: '關閉',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            $('#dd_dg').window('close');
                        }
                    }]
                });
            }
        }
    </script>
</head>
<body>
<!-- datagrid -->
<table id="tab"></table>
<!-- 添加窗體 -->
<div id="dd_dg" style="display:none;" >
    <form id="fm_dg" method="post" action="grid.ashx">
        <input type="hidden" name="id" id="id"/>
        編號:<input type="text" name="no" id="no" class="easyui-validatebox"  required="true"/><br/>
        姓名:<input type="text" name="name" id="name" class="easyui-validatebox"  required="true"/><br/>
        密碼:<input type="password" name="pwd" id="pwd" class="easyui-validatebox"  required="true"/><br/>
        性別:<select name="sex" id="sex">
                      <option value="1">男</option>
                      <option value="0">女</option>
                </select><br/>
        年齡:<input type="text" name="age" id="age" class="easyui-validatebox"  required="true"/><br/>
        住址:<input type="text" name="address" id="address" class="easyui-validatebox"  required="true"/><br/>
    </form>
</div>
</body>
</html>
//後臺數據處理頁面grid.ashx
public class grid : IHttpHandler
    {
        public void Proce***equest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"].ToString();
            switch (action)
            {
                case "query":
                    Query();
                    break;
                case "del":
                    Del();
                    break;
                case "add":
                    Add();
                    break;
                case "edit":
                    Edit();
                    break;
            }
        }
        /// <summary>
        /// 查詢並分頁
        /// </summary>
        private void Query()
        {
            string str = string.Empty;
             string rows = HttpContext.Current.Request["rows"].ToString();  //獲取datagrid傳來的行數
            string page = HttpContext.Current.Request["page"].ToString(); //獲取datagrid傳來的頁碼 當前頁
            // GetTablebyproc上篇文章的調用帶參數的存儲過程,返回datat
            DataTable dt1 = SqlHelper.GetTablebyproc("pageFileter", int.Parse(rows), int.Parse(page), "stu");
            DataTable dt = SqlHelper.GetTable("select * from stu");
            str = JSonHelper.CreateJsonParameters(dt1, true, dt.Rows.Count);
            HttpContext.Current.Response.Write(str);
        }
        /// <summary>
        /// 刪除一行數據
        /// </summary>
        private void Del()
        {
            string str = "刪除失敗";
            string id = HttpContext.Current.Request["id"] != "" ? HttpContext.Current.Request["id"].ToString() : "";
            if (id != string.Empty)
            {
                int num = SqlHelper.DelData("stu", id);
                if (num > 0)
                {
                    str = string.Format("刪除成功,本次共刪除{0}條", num.ToString());
                }
                else
                {
                    str = "刪除失敗";
                }
            }
            HttpContext.Current.Response.Write(str);
        }
        /// <summary>
        /// 添加一條數據
        /// </summary>
        private void Add()
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in HttpContext.Current.Request.Form.AllKeys)
            {
                sb.AppendFormat("{0}: {1}\n", s, HttpContext.Current.Request.Form[s]);
            }
            string str = sb.ToString();
            string[] str1 = str.Split('&');
            string no = str1[1].Split('=')[1];
            string name = str1[2].Split('=')[1];
            string pwd = str1[3].Split('=')[1];
            string sex = str1[4].Split('=')[1]=="1"?"男":"女";
            int age = int.Parse(str1[5].Split('=')[1]);
            string add = str1[6].Split('=')[1];
            string address = add.Substring(0, add.Length - 1);
            string sql = string.Format("insert into stu values('{0}','{1}','{2}','{3}',{4},'{5}')", no, name, pwd, sex, age, address);
            int count = 0;
            count = SqlHelper.ExeNonQuery(sql, CommandType.Text, null) ? 1 : 0;
            if (count > 0)
            {
                HttpContext.Current.Response.Write("ok");
            }
            else
            {
                HttpContext.Current.Response.Write("no");
            }
        }
        /// <summary>
        /// 修改一條數據
        /// </summary>
        private void Edit()
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in HttpContext.Current.Request.Form.AllKeys)
            {
                sb.AppendFormat("{0}: {1}\n", s, HttpContext.Current.Request.Form[s]);
            }
            string str = sb.ToString();
            string[] str1 = str.Split('&');
            int id = int.Parse(str1[0].Split('=')[1]);
            string no = str1[1].Split('=')[1];
            string name = str1[2].Split('=')[1];
            string pwd = str1[3].Split('=')[1];
            string sex = str1[4].Split('=')[1] == "1" ? "男" : "女";
            int age = int.Parse(str1[5].Split('=')[1]);
            string add = str1[6].Split('=')[1];
            string address = add.Substring(0, add.Length - 1);
            string sql = string.Format("update stu set no='{0}',name='{1}',pwd='{2}',sex='{3}',age={4},address='{5}' where id={6}", no, name, pwd, sex, age, address, id);
            int count = 0;
            count = SqlHelper.ExeNonQuery(sql, CommandType.Text, null) ? 1 : 0;
            if (count > 0)
            {
                HttpContext.Current.Response.Write("ok");
            }
            else
            {
                HttpContext.Current.Response.Write("no");
            }
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章