前言
- 上一篇文章我們完成了系統角色管理的基本功能實現,也對系統層次結構進行了了解。這一篇我們將繼續對系統的用戶管理模塊進行代碼編寫。代碼沒有做封裝,所以大部分的邏輯代碼都是相通的,只是在一些前端的細節上處理有些不同。源碼將在文章的末尾給出,有興趣的園友可以對代碼做一些封裝或重構,畢竟這可以減少很多的代碼量。
Abstract層
- 在這一層添加對用戶管理操作的業務接口IS_UserRepository,里面定義增刪改查的業務接口。代碼如下:
using Entities; using System.Collections.Generic; namespace Abstract { public interface IS_UserRepository { bool Add(S_User model); bool Update(S_User model); bool Delete(long id); List<S_User> GetInfo(string strWhere, int rows, int page, out int total); } }
Concrete層
- 這一層我們添加S_UserRepository類,實現用戶管理需要的操作方法。由於在頁面上操作需要顯示用戶所屬的角色信息,所以在這里的查詢會啟用延遲加載。代碼如下:
using System.Collections.Generic; using System.Linq; using Abstract; using Entities; namespace Concrete { public class S_UserRepository : IS_UserRepository { private EFDbContext context = new EFDbContext(); public bool Add(S_User model) { try { if (null != model) { context.S_Users.Add(model); context.SaveChanges(); return true; } else { return false; } } catch { return false; } } public bool Update(S_User model) { try { if (null != model) { S_User oldModel = context.S_Users.FirstOrDefault(x => x.ID == model.ID); //oldModel.UserName = model.UserName; //oldModel.UserPwd = model.UserPwd; oldModel.Email = model.Email; oldModel.IsUse = model.IsUse; oldModel.Phone = model.Phone; oldModel.Remark = model.Remark; oldModel.RoleID = model.RoleID; context.SaveChanges(); return true; } else { return false; } } catch { return false; } } public bool Delete(long id) { try { if (null != id) { S_User model = context.S_Users.FirstOrDefault(x => x.ID == id); if (null != model) { context.S_Users.Remove(model); context.SaveChanges(); return true; } else { return false; } } else { return false; } } catch { return false; } } public List<S_User> GetInfo(string strWhere, int rows, int page, out int total) { context.Configuration.ProxyCreationEnabled = true; context.Configuration.LazyLoadingEnabled = true; List<S_User> listData = new List<S_User>(); if (!string.IsNullOrEmpty(strWhere)) { listData = context.S_Users.Where(x => x.UserName.Contains(strWhere)).ToList(); } else { listData = context.S_Users.ToList(); } var results = listData.OrderByDescending(p => p.ID).Skip((page - 1) * rows).Take(rows); total = listData.Count(); return results.ToList(); } } }
Web層
- 首先在NinjectControllerFactory類中追加對用戶管理的解耦操作的綁定,代碼如下:
private void AddBindings() { // put additional bindings here ninjectKernel.Bind<IS_RoleRepository>().To<S_RoleRepository>(); ninjectKernel.Bind<IS_UserRepository>().To<S_UserRepository>(); }
- 在MVC的Models中定義頁面需要綁定的數據模型對象,這里我們將數據模型類都定義在mod_S_User類中。mod_S_User和mod_S_UserPage用於綁定EasyUI的datagrid中的數據集合。RoleData用戶綁定EasyUI的combobox下拉框中的角色列表。代碼如下:
using System.Collections.Generic; namespace Web.Models { public class mod_S_User { public long ID { get; set; } public long RoleID { get; set; } public string RoleName { get; set; } public string UserName { get; set; } public string UserPwd { get; set; } public string IsUse { get; set; } public string Phone { get; set; } public string Email { get; set; } public string Remark { get; set; } } public class RoleData { public long RoleID { get; set; } public string RoleName { get; set; } } public class mod_S_UserPage { public string total { get; set; } public List<mod_S_User> rows { get; set; } } }
- 在MVC的SystemController中添加對用戶管理接口IS_UserRepository的依賴注入,代碼如下:
private IS_RoleRepository IS_Role; private IS_UserRepository IS_User; public SystemController(IS_RoleRepository _S_Role, IS_UserRepository _S_User) { this.IS_Role = _S_Role; this.IS_User = _S_User; }
- 在MVC的SystemController中完成對用戶管理操作的頁面邏輯處理代碼。代碼如下:
#region log20150704 Create By Jack:系統用戶操作 public ActionResult UserList() { return View(); } public ActionResult GetUsers(string strWhere, int rows, int page = 1) { mod_S_UserPage DataModel = new mod_S_UserPage(); List<mod_S_User> listViewData = new List<mod_S_User>(); int total; //必須定義參數變量接收out參數 List<S_User> listData = IS_User.GetInfo(strWhere, rows, page, out total); foreach (var item in listData) { mod_S_User model = new mod_S_User(); model.ID = item.ID; model.UserName = item.UserName; model.UserPwd = item.UserPwd; model.RoleID = item.S_Role.ID; model.RoleName = item.S_Role.RoleName; model.IsUse = item.IsUse; model.Email = item.Email; model.Phone = item.Phone; model.Remark = item.Remark; listViewData.Add(model); } DataModel.total = total.ToString(); DataModel.rows = listViewData; return Json(DataModel, JsonRequestBehavior.AllowGet); } public ActionResult CreateUser(S_User dataModel) { bool rtnFalg = false; if (Request.IsAjaxRequest()) { if (dataModel.ID == 0) //0為ID的默認值 { dataModel.ID = NewID.NewComb(); rtnFalg = IS_User.Add(dataModel); } else { rtnFalg = IS_User.Update(dataModel); } if (rtnFalg == true) { return Json(new { flag = true }); } else { return Json(new { flag = false }); } } else { return Json(new { flag = false }); } } [HttpPost] public ActionResult DeleteUser(long id) { if (id != 0) { bool rtnFlag = IS_User.Delete(id); if (rtnFlag == true) { return Json(new { flag = true }); } else { return Json(new { flag = false }); } } else { return Json(new { flag = false }); } } public ActionResult BindRoles() { List<S_Role> listData = IS_Role.BindRoles(); List<RoleData> BindData = new List<RoleData>(); foreach (var item in listData) { RoleData model = new RoleData(); model.RoleID = item.ID; model.RoleName = item.RoleName; BindData.Add(model); } return Json(BindData, JsonRequestBehavior.AllowGet); } #endregion
- 注意綁定頁面角色下拉框中的角色列表的方法是定義在IS_RoleRepository中的,所以應該在S_RoleRepository中追加該方法的實現,代碼如下:
public List<S_Role> BindRoles() { context.Configuration.ProxyCreationEnabled = false; context.Configuration.LazyLoadingEnabled = false; List<S_Role> listData = new List<S_Role>(); listData = context.S_Roles.ToList(); return listData; }
- 添加對頁面用戶管理視圖UserList的代碼,在此頁面有兩個注意的地方:
- 頁面的密碼輸入,需要驗證兩次輸入的密碼是否相等,這個可以通過Jquery的擴展方法解決。代碼如下:
$.extend($.fn.validatebox.defaults.rules, { equalTo: { validator: function (value, param) { return $(param[0]).val() == value; }, message: '字段不匹配' } });
2. 頁面的角色下拉框列表綁定是動態的,需要從數據庫中讀取。利用combobox的data-options屬性,
我們可以向Controller中發起異步的get請求加載數據。代碼如下:
<input class="easyui-combobox" id="RoleID" required="true" name="RoleID" data-options=" url:'/System/BindRoles', method:'get', valueField:'RoleID', textField:'RoleName', panelHeight:'auto', width:134">
3. UserList的完整代碼如下:
@{ ViewBag.Title = "UserList"; } <script src="~/JSFunction/System_UserList.js"></script> <style type="text/css"> #fm { margin: 0; padding: 10px 30px; } .ftitle { font-size: 14px; font-weight: bold; padding: 5px 0; margin-bottom: 10px; border-bottom: 1px solid #ccc; } .fitem { margin-bottom: 5px; } .fitem label { display: inline-block; width: 80px; } </style> <div id="toolbar"> <table cellpadding="2"> <tr> <td>用戶ID:<input type="hidden" id="hid_optype" name="hid_optype" value="" /></td> <td><input class="easyui-validatebox textbox" type="text" name="ID" disabled="disabled"></input></td> <td>用戶名:</td> <td><input class="easyui-validatebox textbox" type="text" name="UserName" id="txt_UserName"></input></td> </tr> </table> <div class="panelExten"> <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-search" plain="true" onclick="ConditionSearch();">查詢</a> | <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" plain="true" onclick="NewData();">新增</a> | <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-edit" plain="true" onclick="EditData();">編輯</a> | <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-remove" plain="true" onclick="DestroyData();">刪除</a> | <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-undo" plain="true" onclick="ClearQuery();">清除</a> </div> </div> <table id="dg" class="easyui-datagrid" pagination="true" rownumbers="true" fit="true" fitcolumns="true" singleselect="true" toolbar="#toolbar" @*data-options="toolbar:toolbar" *@ fit="false" style=" height:500px;"> <thead> <tr> <th data-options="field:'ck',checkbox:true"></th> <th field="ID" width="50"> 主鍵ID </th> <th field="UserName" width="50"> 用戶名 </th> <th field="Phone" width="50"> 電話 </th> <th field="Email" width="50"> 郵箱 </th> <th field="RoleID" width="50" hidden="true"> 角色ID </th> <th field="RoleName" width="50"> 所屬角色 </th> <th field="Remark" width="150"> 備注 </th> </tr> </thead> </table> <div id="dlg" class="easyui-dialog" style="width: 550px; height: 480px; padding: 10px 20px" closed="true" buttons="#dlg-buttons" modal="true"> <form id="fm" method="post" novalidate> <div class="fitem" style=" display:none;"> <label> 主鍵ID:</label> <input id="ID" name="ID" class="easyui-validatebox" required="true"> </div> <div class="fitem"> <label>用戶名:</label> <input id="UserName" name="UserName" class="easyui-validatebox" required="true"> </div> <div class="fitem" id="div_UserPwd"> <label>密 碼:</label> <input id="UserPwd" name="UserPwd" class="easyui-validatebox" required="true" type="password"> </div> <div class="fitem" id="div_repassword"> <label>確認密碼:</label> <input name="repassword" id="repassword" class="easyui-validatebox" required="true" type="password" validtype="equalTo['#UserPwd']" invalidmessage="兩次輸入密碼不匹配" /> </div> <div class="fitem"> <label>是否啟用:</label> <select class="easyui-combobox" name="IsUse" id="IsUse" style="width:134px;" required="true"> <option value="是" selected>是</option> <option value="否">否</option> </select> </div> <div class="fitem"> <label>所屬角色:</label> <input class="easyui-combobox" id="RoleID" required="true" name="RoleID" data-options=" url:'/System/BindRoles', method:'get', valueField:'RoleID', textField:'RoleName', panelHeight:'auto', width:134 "> </div> <div class="fitem"> <label>郵箱:</label> <input name="Email" id="Email" class="easyui-validatebox" data-options="prompt:'請輸入正確的郵箱地址',validType:'email'"> </div> <div class="fitem"> <label>電話:</label> <input id="Phone" name="Phone" class="easyui-textbox"> </div> <div class="fitem"> <label>備注:</label> <textarea id="Remark" name="Remark" cols="50" rows="4"> </textarea> </div> </form> </div> <div id="dlg-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" id="send" onclick="SaveData()"> 保存</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">取消</a> </div>
- 在JSFunction文件中添加對UserList頁面邏輯處理的js文件System_UserList。代碼如下:
//判斷密碼值是否相等 $.extend($.fn.validatebox.defaults.rules, { equalTo: { validator: function (value, param) { return $(param[0]).val() == value; }, message: '字段不匹配' } }); //頁面加載時讀取數據 $(function () { Search(); var dg = $('#dg'); var opts = dg.datagrid('options'); var pager = dg.datagrid('getPager'); pager.pagination({ onSelectPage: function (pageNum, pageSize) { opts.pageNumber = pageNum; opts.pageSize = pageSize; pager.pagination('refresh', { pageNumber: pageNum, pageSize: pageSize }); Search(); //從數據庫中獲取數據,並加載 }, pageList: [10, 20, 50], //可以設置每頁記錄條數的列表 beforePageText: '第', //頁數文本框前顯示的漢字 afterPageText: '頁 共 {pages} 頁', displayMsg: '當前顯示 {from} - {to} 條記錄 共 {total} 條記錄' }); }); //從數據庫中獲取數據,並加載 function Search() { var page_Number = $('#dg').datagrid('options').pageNumber; //pageNumber為datagrid的當前頁碼 var page_Size = $('#dg').datagrid('options').pageSize; //pageSize為datagrid的每頁記錄條數 var optype = $('#hid_optype').val(); $('#dg').datagrid("loading"); //根據操作類型判斷篩選條件 var strUserName = $('#txt_UserName').val(); var strWhere = strUserName; $.post('/System/GetUsers', { strWhere: strWhere, page: page_Number, rows: page_Size }, function (data) { $('#dg').datagrid('loadData', data); $('#dg').datagrid("loaded"); }) } function ConditionSearch() { $('#hid_optype').val(2); //操作:點擊查詢按鈕篩選條件 Search(); } function NewData() { $('#dlg').dialog('open').dialog('setTitle', '新增用戶信息'); //$('#fm').form('clear'); //頁面上有綁定值,不能完全清空 $('#UserName').val(""); $('#UserPwd').val(""); $('#repassword').val(""); $('#Email').val(""); $('#Phone').val(""); $('#Remark').val(""); } function EditData() { var row = $('#dg').datagrid('getSelected'); if (row) { $('#dlg').dialog('open').dialog('setTitle', '編輯用戶信息'); $("#UserName").attr("disabled", true); $('#div_repassword').hide(); $('#div_UserPwd').hide(); $('#fm').form('load', row); } } function DestroyData() { var row = $('#dg').datagrid('getSelected'); if (row) { $.messager.confirm('提醒', '確定刪除這條數據嗎?', function (r) { if (r) { var strWhere = row.ID; $.ajax({ url: '/System/DeleteUser', type: 'POST', data: { id: strWhere }, success: function (data) { var t = data.flag; if (t) { $.messager.show({ title: '提示信息', msg: '【系統提示】:操作成功!', style: { right: '', top: document.body.scrollTop + document.documentElement.scrollTop, bottom: '' } }); //$('#dg_CommGreen').datagrid('reload'); // reload the user data Search(); } } }) } }); } else { $.messager.show({ title: '提示信息', msg: '【系統提示】:請選擇須要操作的數據!', style: { right: '', top: document.body.scrollTop + document.documentElement.scrollTop, bottom: '' } }); } } function ClearQuery() { $('#txt_UserName').val(""); } function SaveData() { var prod = { ID: $('#ID').val(), UserName: $('#UserName').val(), UserPwd: $('#UserPwd').val(), IsUse: $('#IsUse').combobox('getValue'), RoleID: $('#RoleID').combobox('getValue'), Email: $('#Email').val(), Phone: $('#Phone').val(), Remark: $('#Remark').val() }; $.ajax({ url: '/System/CreateUser', type: 'POST', data: JSON.stringify(prod), dataType: 'json', processData: false, contentType: 'application/json;charset=utf-8', complete: function (data) { $('#dlg').dialog('close'); // close the dialog $('#dg').datagrid('reload'); // reload the user data }, success: function (data) { var t = data.flag; if (t) { $.messager.show({ title: '提示信息', msg: '【系統提示】:操作成功!', style: { right: '', top: document.body.scrollTop + document.documentElement.scrollTop, bottom: '' } }); Search(); //添加成功后加載數據 } else { $.messager.show({ title: '提示信息', msg: '【系統提示】:操作失敗!', style: { right: '', top: document.body.scrollTop + document.documentElement.scrollTop, bottom: '' } }); } }, error: function () { $.messager.show({ title: '提示信息', msg: '【系統提示】:操作失敗!', style: { right: '', top: document.body.scrollTop + document.documentElement.scrollTop, bottom: '' } }); } }); }
- 到此,用戶管理模塊完成,運行結果如下:
備注
- 這一篇,我們完成了用戶管理操作的代碼編寫,后面還有菜單管理和權限設置。代碼都很基礎,不過因為都是采用的異步處理,所以有些細節點還是要注意。源碼已放入網盤,點此下載。整個運行效果如下: