前端代码:
<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'); }*/ });
<divid="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> </td></tr> <tr><td>关键词:</td><td><input name="keywords"class="easyui-validatebox"required="true" /> </td><td> </td></tr> <tr><td>描述:</td><td><input name="description"class="easyui-validatebox"required="true" /> </td><td> </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>
//增加 functionAdd() { $("#dlg").dialog("open").dialog('setTitle', '增加新文章'); $("#fm").form("clear"); $("#btnSave").click(AddSubmit);//绑定保存按钮的事件 } //修改 functionEdit() { varrow =$("#dg").datagrid("getSelected"); if(row) { $("#dlg").dialog("open").dialog('setTitle', '修改文章'); $("#fm").form("load", row); } } functionAddSubmit() { $("#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("提示信息", "操作失败"); } } }); } //删除 functionDelete() { varrow =$('#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>
后端代码:
namespaceEasyuiStudy { /// <summary> ///DataGrid 的摘要说明 /// </summary> public classDataGrid : IHttpHandler { private string connstring = ""; public voidProcessRequest(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 boolIsReusable { get{ return false; } } //分页查询 private voidquery(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 voidadd(HttpContext context) { string title = context.Request["title"]; string keywords = context.Request["keywords"]; string description = context.Request["description"]; MySqlHelper mysqldb = newMySqlHelper(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 voiddelete(HttpContext context) { string id = context.Request["id"]; MySqlHelper mysqldb = newMySqlHelper(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,intRowCount) { MySqlHelper mysqldb = newMySqlHelper(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); returnjson; } } }
DataTable转成DataGrid能够识别的json:
public classEasyuiDataGrid { #region dataTable转换成Json格式 /// <summary> ///dataTable转换成Json格式 /// </summary> /// <paramname="dt"></param> ///<returns></returns> public static string DataTable2Json(DataTable dt,int total=-1) { StringBuilder jsonBuilder = newStringBuilder(); 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("]}"); returnjsonBuilder.ToString(); } #endregion dataTable转换成Json格式}