zoukankan      html  css  js  c++  java
  • C# 配合 Easyui DataGrid 实现增删改查 通用模板

    前端代码:

    <table id="DataGridEmployee" data-options="region:'center',title:'员工列表'"></table>          
      $('#DataGridEmployee').datagrid({
                    title: '员工列表',
                    //iconCls: 'icon-edit',//图标
                     700,
                    height: 'auto',
                    nowrap: false,
                    striped: true,
                    border: true,
                    collapsible: false,//是否可折叠的
                    fit: true,//自动大小
                    url: 'personnel/OrgManage.ashx?action=GetEmployeeList',
                    //sortName: 'id',
                    //sortOrder: 'desc',
                    remoteSort: false,
                    idField: 'fldId',
                    checkOnSelect: false,
                    selectOnCheck :false,
                    singleSelect: true,//是否单选
                    pagination: true,//分页控件
                    rownumbers: true,//行号
                    frozenColumns: [[
                      { field: 'ck', checkbox: true }
                    ]],
                    //-----------------------------------------------
                    toolbar: [{
                        text: '添加',
                        iconCls: 'icon-add',
                        handler: function () {
                            OpendlgEditEmployee('','');
                        }
                    }, '-', {
                        text: '修改',
                        iconCls: 'icon-edit',
                        handler: function () {
                            OpendlgEditEmployee('ModifyEmployee', $('#DataGridEmployee').datagrid('getSelected').id);
                        }
                    }, '-', {
                        text: '删除',
                        iconCls: 'icon-remove',
                        handler: function () {
                            DeleteEmployee();
                        }
                    }, '-', {
                        text: '显示所有',
                        iconCls: 'icon-application_view_icons',
                        handler: function () {
                            GetAllEmployeeList();
                        }
                    }],
                    //------------------------------------------------------
                    columns: [[
                    { field: 'id', title: '员工ID',50},
                    { field: 'realname', title: '姓名',80 },
                    { field: 'depart', title: '所属部门',150 },
                    {
                        field: 'sex', title: '性别',40, formatter: function (value, rowData, rowIndex) {
                            if (value = '0') {
                                return '男';
                            }
                            else {
                                return '女';
                            }
                        }
                    },
                    { field:'birthday',title:'生日',80},
                    { field: 'mobile', title: '手机',80 },
                    { field: 'email', title: '邮箱' ,150},
                    { field: 'idcard', title: '身份证',  150 },
                    {
                        field: 'updatetime', title: '更新时间',  200
                    }
                    ]],
                    onLoadSuccess: function () {
                        $('#center  .panel-header').first().remove();//删除一个标题栏
                    }
                }).datagrid('getPager').pagination({
                    //设置分页控件
                    pageSize: 10,//每页显示的记录条数,默认为10
                    pageList: [5, 10, 15],//可以设置每页记录条数的列表
                    beforePageText: '第',//页数文本框前显示的汉字
                    afterPageText: '页    共 {pages} 页',
                    displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',
                    /*onBeforeRefresh:function(){
                        $(this).pagination('loading');
                        alert('before refresh');
                        $(this).pagination('loaded');
                    }*/
                });
     <div id="dlg" class="easyui-dialog" closed="true">   
    <form id="fm" method="post"> <table style="100%;"> <tr><td>标题:</td><td><input name="title" class="easyui-validatebox" required="true" /> </td><td>&nbsp;</td></tr> <tr><td>关键词:</td><td><input name="keywords" class="easyui-validatebox" required="true" /> </td><td>&nbsp;</td></tr> <tr><td>描述:</td><td><input name="description" class="easyui-validatebox" required="true" /> </td><td>&nbsp;</td></tr> </table> </form> <div id="dlg-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" id="btnSave" iconcls="icon-save">保存</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#dlg').dialog('close')" iconcls="icon-cancel">取消</a> </div> </div>
    //增加
            function Add()
            {
                $("#dlg").dialog("open").dialog('setTitle', '增加新文章');
                $("#fm").form("clear");
                $("#btnSave").click(AddSubmit);//绑定保存按钮的事件
            }
            //修改
            function Edit()
            {
                var row = $("#dg").datagrid("getSelected");
                if (row) {
                    $("#dlg").dialog("open").dialog('setTitle', '修改文章');
                    $("#fm").form("load", row);
                }
            }
    
            function AddSubmit()
            {
                $("#fm").form("submit", {
                    url: "DataGrid.ashx?action=add",
                    onsubmit: function () {
                        return $(this).form("validate");
                    },
                    success: function (result) {
                        if (result == "1") {
                            $.messager.alert("提示信息", "操作成功");
                            $("#dlg").dialog("close");
                            $("#dg").datagrid("load");
                        }
                        else {
                            $.messager.alert("提示信息", "操作失败");
                        }
                    }
                });
            }
            //删除
            function Delete()
            {
                var row = $('#dg').datagrid('getSelected');
                if (row) {
                    $.messager.confirm('Confirm', '确定要删除这条记录吗?', function (r) {
                        if (r) {
                            $.post('DataGrid.ashx', { action:'delete', id: row.id }, function (result) {
                                if (result) {
                                    $('#dg').datagrid('reload').datagrid('unselectAll');    // 重新加载数据 
                                } else {
                                    $.messager.show({   // 出错提示
                                        title: 'Error',
                                        msg: result.errorMsg
                                    });
                                }
                            }, 'json');
                        }
                    });
                }
            }
        </script>

    后端代码:

    namespace EasyuiStudy
    {
        /// <summary>
        /// DataGrid 的摘要说明
        /// </summary>
        public class DataGrid : IHttpHandler
        {
            private string connstring = "";
    
            public void ProcessRequest(HttpContext context)
            {
                string title = context.Request["title"];
                string action = context.Request["action"];
                switch (action) 
                {
                    case "add": add(context);
                                 break;
    
                    case "delete": delete(context);
                                  break;
    
                    default:query(context);
                                  break;
                    
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
    
            //分页查询
            private void query(HttpContext context)
            {
    
                string rows = context.Request["rows"];
                string page = context.Request["page"];
                int intRowCount = 10;
                int intPageIndex = 1;
                if (rows != null && rows != "0")
                {
                    intRowCount = Convert.ToInt32(rows);
                }
                if (page != null && page != "0")
                {
                    intPageIndex = Convert.ToInt32(page);
                }
    
                context.Response.ContentType = "text/plain";
                context.Response.Write(MyQuery(intPageIndex, intRowCount));
            
            }
            //增加
            private void add(HttpContext context)
            {
                string title = context.Request["title"];
                string keywords = context.Request["keywords"];
                string description = context.Request["description"];
    
                MySqlHelper mysqldb = new MySqlHelper(connstring);
                string sql = string.Format("insert into `hdm1140428_db`.`v9_news` (title,keywords,description) values('{0}','{1}','{2}')",title,keywords,description);
                int i=mysqldb.ExecuteNonQuery(sql);
    
                context.Response.ContentType = "text/plain";
                context.Response.Write(i.ToString());
            }
    
            //删除一条记录
            private void delete(HttpContext context)
            {
                string id = context.Request["id"];
    
                MySqlHelper mysqldb = new MySqlHelper(connstring);
                string sql = string.Format("delete from `hdm1140428_db`.`v9_news` where id={0}",id);
                int i = mysqldb.ExecuteNonQuery(sql);
    
    
                context.Response.ContentType = "text/plain";
                context.Response.Write(i.ToString());
            }
    
            private string MyQuery(int PageIndex,int RowCount)
            {
                MySqlHelper mysqldb = new MySqlHelper(connstring);
                //获得总记录数 
                string sql = "select Count(*) total from `hdm1140428_db`.`v9_news`";
                DataTable dt=mysqldb.ExecuteDataTable(sql);
                int total = Convert.ToInt32(dt.Rows[0].ItemArray[0].ToString()) ;
                sql = string.Format("select *     FROM `hdm1140428_db`.`v9_news` order by id desc  limit {0},{1} ", (PageIndex - 1) * RowCount, RowCount);
                dt = mysqldb.ExecuteDataTable(sql);
                string json=EasyuiDataGrid.DataTable2Json(dt,total);
                return json;
                
            }
    
        }
    }

    DataTable转成DataGrid能够识别的json:

     public class EasyuiDataGrid
        { 
            #region dataTable转换成Json格式
            /// <summary> 
            /// dataTable转换成Json格式 
            /// </summary> 
            /// <paramname="dt"></param> 
            ///<returns></returns> 
            public static string DataTable2Json(DataTable dt,int total=-1)
            {
                StringBuilder jsonBuilder = new StringBuilder();
                jsonBuilder.Append("{"total":");
                if (total == -1)
                {
                    jsonBuilder.Append(dt.Rows.Count);
                }
                else
                {
                    jsonBuilder.Append(total);
                } 
                jsonBuilder.Append(","rows":[");
    
                for (int i = 0; i <dt.Rows.Count; i++)
                {
                   jsonBuilder.Append("{");
                    for (int j = 0; j <dt.Columns.Count; j++)
                    {
                       jsonBuilder.Append(""");
                       jsonBuilder.Append(dt.Columns[j].ColumnName);
                       jsonBuilder.Append("":"");
                       jsonBuilder.Append(dt.Rows[i][j].ToString());
                       jsonBuilder.Append("",");
                    }
                    if (dt.Columns.Count > 0)
                    {
                       jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    }
                   jsonBuilder.Append("},");
                }
                if (dt.Rows.Count > 0)
                {
                   jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                }
                jsonBuilder.Append("]}");  
                return jsonBuilder.ToString();
            }
            #endregion dataTable转换成Json格式
        }
  • 相关阅读:
    一个利用扩展方法的实例:AttachDataExtensions
    正则表达式语法
    正则表达式30分钟入门教程
    js正则验证两位小数 验证数字最简单正则表达式大全
    SQL Server DBA三十问【转】
    Vue(踩坑)vue.esm.js?efeb:628 [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in
    vue(有必要做的项目优化)
    vue_(根据多种条件过滤评论内容)
    vue(ref父组件使用子组件中定义的方法)
    Vuex(实现加减操作,Vue.set解决自定义属性没有双向数据绑定)
  • 原文地址:https://www.cnblogs.com/southhuachen/p/5513810.html
Copyright © 2011-2022 走看看