前言 ?
在接下來的篇幅里將對系統的模塊功能進行編寫。主要以代碼實現為主。這一篇我們需要完成系統模塊“角色管理”的相關功能。完成后可以對系統框架結構有進一步了解。 ?
Abstract 層 ?
之前說過,Abstract層是對業務接口的定義,所以我們新建接口文件IS_UserRepository,定義增刪改查業務的接口。這一層需要添加對Entities層的引用。代碼如下: using Entities;
using System.Collections.Generic; namespace Abstract
{ public interface IS_RoleRepository{ bool Add(S_Role model); bool Update(S_Role model); bool Delete(
long id);List <S_Role> GetInfo(
string strWhere,
int rows,
int page,
out int total);}
} ?
Concrete 層 ?
這一層是對Abstract業務的接口進行實現層,也是利用EntityFramework與數據庫進行交互的層。我們定義類文件S_ RoleRepository,實現增刪改查業務。查詢時,我們將禁用延遲加載。這一層需要添加對Entities、Abstract層的引用。代碼如下: using System.Collections.Generic;
using System.Linq;
using Abstract;
using Entities; namespace Concrete
{ public class S_RoleRepository : IS_RoleRepository{ private EFDbContext context =
new EFDbContext(); public bool Add(S_Role model){ try { if (
null !=
model){context.S_Roles.Add(model);context.SaveChanges(); return true ;} else { return false ;}} catch { return false ;}} public bool Update(S_Role model){ try { if (
null !=
model){S_Role oldModel = context.S_Roles.FirstOrDefault(x => x.ID ==
model.ID);oldModel.RoleName =
model.RoleName;oldModel.Remark =
model.Remark;context.SaveChanges(); return true ;} else { return false ;}} catch { return false ;}} public bool Delete(
long id){ try { if (id !=
0 ){S_Role model = context.S_Roles.FirstOrDefault(x => x.ID ==
id); if (
null !=
model){context.S_Roles.Remove(model);context.SaveChanges(); return true ;} else { return false ;}} else { return false ;}} catch { return false ;}} public List<S_Role> GetInfo(
string strWhere,
int rows,
int page,
out int total){context.Configuration.ProxyCreationEnabled =
false ;context.Configuration.LazyLoadingEnabled =
false ;List <S_Role> listData =
new List<S_Role>
(); if (!
string .IsNullOrEmpty(strWhere)){listData = context.S_Roles.Where(x =>
x.RoleName.Contains(strWhere)).ToList();} else {listData =
context.S_Roles.ToList();} var results = listData.OrderByDescending(p => p.ID).Skip((page -
1 ) *
rows).Take(rows);total =
listData.Count(); return results.ToList();}}
} ?
利用 Ninject 實現依賴注入 ?
Ninject是.net平臺下的一個IOC/DI框架。在此我們可以利用它解除Concrete對Abstract的強依賴關系。我們通過Ninject可以在web層構建一個依賴注入列表,這樣可以在運行時進行依賴呢,而不是在編譯時就產生依賴關系。 接下來,我們為Web層添加Ninject,可以在Nuget上通過“程序包管理器控制臺”進行下載安裝。如下圖:
在Web層建立Infrastructure文件夾,添加NinjectControllerFactory類,實現Concrete和Abstract的動態綁定,在這里我們采用的是Ninject的構造注入的方式。這一層需要添加對Abstract、Concrete的引用。代碼如下: using Abstract;
using Concrete;
using Ninject;
using System;
using System.Web.Mvc;
using System.Web.Routing; namespace Web.Controllers
{ public class NinjectControllerFactory : DefaultControllerFactory{ private IKernel ninjectKernel; public NinjectControllerFactory(){ninjectKernel =
new StandardKernel();AddBindings();} protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType){ return controllerType ==
null ?
null : (IController)ninjectKernel.Get(controllerType);} private void AddBindings(){ // put additional bindings here ninjectKernel.Bind<IS_RoleRepository >().To<S_ RoleRepository > (); }}
} ?
打開Web層的Global.asax文件,添加對動態生成控制器工廠類NinjectControllerFactory的注冊。代碼如下: public class MvcApplication : System.Web.HttpApplication{ protected void Application_Start(){AreaRegistration.RegisterAllAreas();WebApiConfig.Register(GlobalConfiguration.Configuration);FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);DatabaseInitializer.Initialize(); ControllerBuilder.Current.SetControllerFactory( new NinjectControllerFactory()); }} ?
實現 Web 層角色管理界面功能 ?
注意:本示例都將采用Jquery的Ajax的異步方式,視圖和控制器都將采用Json字符串作為傳輸對象。如果對這兩塊不清楚,可以先查閱相關資料了解一下。 我們先定義MVC的Models層,新增mod_S_Role類,用于EasyUI的datagrid綁定role對象和分頁操作。代碼如下: using Entities;
using System.Collections.Generic; namespace Web.Models
{ public class mod_S_RolePage{ public string total {
get ;
set ; } public List<S_Role> rows {
get ;
set ; }}
} 再完成MVC的Controllers,新增SystemController控制器,添加角色操作界面視圖RoleList,完成SystemController的角色操作代碼。代碼如下: using System.Collections.Generic;
using System.Web.Mvc;
using Abstract;
using Common;
using Entities;
using Web.Models; namespace Web.Controllers
{ public class SystemController : Controller{ private IS_RoleRepository IS_Role; public SystemController(IS_RoleRepository _S_Role){ this .IS_Role =
_S_Role;} #region log20150703 Create By Jack: 系統角色操作
public ActionResult RoleList(){ return View();} public ActionResult GetRoles(
string strWhere,
int rows,
int page =
1 ){mod_S_RolePage DataModel =
new mod_S_RolePage(); int total;
// 必須定義參數變量接收out參數 List<S_Role> listData = IS_Role.GetInfo(strWhere, rows, page,
out total);DataModel.total =
total.ToString();DataModel.rows =
listData; return Json(DataModel, JsonRequestBehavior.AllowGet);} public ActionResult CreateRole(S_Role dataModel){ bool rtnFalg =
false ; if (Request.IsAjaxRequest()){ if (dataModel.ID ==
0 )
// 0為ID的默認值
{dataModel.ID =
NewID.NewComb();rtnFalg =
IS_Role.Add(dataModel);} else {rtnFalg =
IS_Role.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 DeleteRole(
long id){ if (id !=
0 ){ bool rtnFlag =
IS_Role.Delete(id); if (rtnFlag ==
true ){ return Json(
new { flag =
true });} else { return Json(
new { flag =
false });}} else { return Json(
new { flag =
false });}} #endregion }
} ?
完成MVC的Views,修改RoleList的代碼如下: @{ViewBag.Title =
" RoleList " ;
} <script src=
" ~/JSFunction/System_RoleList.js " ></script><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=
" RoleName " id=
" txt_RoleName " ></input></td></tr></table><div
class =
" panelExten " ><a href=
" javascript:void(0) " class =
" easyui-linkbutton " iconcls=
" icon-search " plain=
" true " οnclick=
" ConditionSearch(); " >查詢</a> |<a href=
" javascript:void(0) " class =
" easyui-linkbutton " iconcls=
" icon-add " plain=
" true " οnclick=
" NewData(); " >新增</a> |<a href=
" javascript:void(0) " class =
" easyui-linkbutton " iconcls=
" icon-edit " plain=
" true " οnclick=
" EditData(); " >編輯</a> |<a href=
" javascript:void(0) " class =
" easyui-linkbutton " iconcls=
" icon-remove " plain=
" true " οnclick=
" DestroyData(); " >刪除</a> |<a href=
" javascript:void(0) " class =
" easyui-linkbutton " iconcls=
" icon-undo " plain=
" true " οnclick=
" ClearQuery(); " >清除</a></div>
</div><table id=
" dg " class =
" easyui-datagrid " pagination=
" true " rownumbers =
" true " fit=
" true " fitcolumns =
" true " singleselect=
" true " 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=
" 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=
" RoleName " name=
" RoleName " class =
" easyui-validatebox " required=
" true " ></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 " οnclick=
" SaveData() " > 保存</a><a href=
" javascript:void(0) " class =
" easyui-linkbutton " iconcls=
" icon-cancel " οnclick=
" javascript:$('#dlg').dialog('close') " >取消</a>
</div>
?
注意,由于頁面都是由大量的JS代碼操作,所以我們在WEB的目錄下建立一個JSFunction文件夾來存放頁面的處理函數,名字由控制器和視圖組合而成,如本例中為System_RoleList.js。代碼如下: // 頁面加載時讀取數據
$(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 strRoleName = $(
' #txt_RoleName ' ).val(); var strWhere =
strRoleName;$.post( ' /System/GetRoles ' , { 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 ' );
}function EditData() { var row = $(
' #dg ' ).datagrid(
' getSelected ' ); if (row) {$( ' #dlg ' ).dialog(
' open ' ).dialog(
' setTitle ' ,
' 編輯角色信息 ' );$( ' #fm ' ).form(
' load ' , row);}
}function DestroyData() { var row = $(
' #dg ' ).datagrid(
' getSelected ' ); if (row) {$.messager.confirm( ' 提醒 ' ,
' 確定刪除這條數據嗎? ' , function (r) { if (r) { var strWhere =
row.ID;alert(strWhere);$.ajax({url: ' /System/DeleteRole ' ,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_RoleName ' ).val(
"" );
}function SaveData() { var prod =
{ID: $( ' #ID ' ).val(),RoleName: $( ' #RoleName ' ).val(),Remark: $( ' #Remark ' ).val()};$.ajax({url: '/System/CreateRole ' ,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: '' }});}});
} ?
?
備注 ?
本示例按照系統框架的層級結構對系統角色管理模塊進行代碼的編寫。完成了基本功能,但沒有對EasyUI做過多詳細的解釋,有關EasyUI的詳細使用方法可以查看官方API。 本示例源碼下載 。通過運行Account控制器下的Login視圖查看系統運行效果:
?
? ? ? ? ?
轉載于:https://www.cnblogs.com/wangweimutou/p/4682445.html
總結
以上是生活随笔 為你收集整理的EF6 CodeFirst+Repository+Ninject+MVC4+EasyUI实践(六) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。