前端代碼:
<table id="DataGridEmployee" data-options="region:'center',title:'員工列表'"></table> $('#DataGridEmployee').datagrid({ title: '員工列表', //iconCls: 'icon-edit',//圖標 width: 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',width:50}, { field: 'realname', title: '姓名',width:80 }, { field: 'depart', title: '所屬部門',width:150 }, { field: 'sex', title: '性別',width:40, formatter: function (value, rowData, rowIndex) { if (value = '0') { return '男'; } else { return '女'; } } }, { field:'birthday',title:'生日',width:80}, { field: 'mobile', title: '手機',width:80 }, { field: 'email', title: '郵箱' ,width:150}, { field: 'idcard', title: '身份證', width: 150 }, { field: 'updatetime', title: '更新時間', width: 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="width: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>
//增加 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格式 }