AngularJS MVC 存储库释放






4.82/5 (97投票s)
这是关于 AngularJS 和 Repository Pattern 用于开发专业 MVC 应用程序的最简单的教程。它包含一个关于实际权限管理项目的源代码。
引言
本文旨在清晰阐述 AngularJS 技术和 Repository,它是用于轻松、专业地开发 Web 应用程序的有用设计模式之一。Jquery 存在一些基本困难,例如代码混乱或陷入死锁,但 AngularJS 能够解决 Jquery 的一些障碍。AngularJS 足够强大,特别是对于 CRUD(创建、读取、更新和删除)Web 应用程序,它遵循 MVC 模式,因此我们的代码整洁清晰。此外,它使我们能够编写更少的代码,并且在 AngularJS 中进行测试代码的条件更好。尽管这些因素并不能减弱 Jquery 在编写其他类型应用程序(如游戏等)方面的强大功能。
本文的另一个重点是解释 Repository Pattern,它封装了数据访问层,并在实际数据库与其他数据访问层部分之间划清界限。它对开发人员有一定的好处,例如,它使得更改和更新数据上下文更加方便,并且测试框架不会针对物理数据访问代码运行,因此这种隔离使其更具灵活性。
最后但同样重要的是,为初学者解释如何在 Web 浏览器中调试脚本。
我将更广泛地描述每个部分,我将在真实项目中打开这些技术和模式,以便从中获得清晰的概念。
背景
什么是 Repository
Repository 是一种有用的设计模式,它隐藏了物理数据,使其不被数据访问层的其他部分访问。专业地说,Repository 指导我们如何将数据上下文与数据库查询和其他数据访问逻辑进行封装。它就像一条线,将实际数据库与其他部分隔离开来,最终使我们的 Web 应用程序在分层测试方面更加方便。此外,它提供了一个类似内存的集合 https://codeproject.org.cn/Articles/832189/List-vs-IEnumerable-vs-IQueryable-vs-ICollection-v,用于访问域对象,从而忽略持久性并提高性能。因此,我们更喜欢在 MVC 应用程序中使用 Repository,以获得可测试性、速度和未来更改的灵活性。
我们有两种 Repository 结构选择。一种是为每个实体构建一个 Repository
类和一个 IRepository
接口,另一种方法是为所有实体创建一个 GenericRepository
类,并定义基本的 CRUD(创建、读取、更新、删除)操作和一个 UnitOfWork
类,以便每个实体的所有 Repository 都应该建立在 UnitOfWork
类之上。显然,当实体过多时,第二种方法是可取的。
正如我们在 MVC 中为每个实体创建一个控制器“XController
”一样,我们创建一个名为 GenericRepository 的文件夹并创建一个名为“GenericRepository.cs”的类。类“GenericRepository.cs”具有处理数据上下文的 CRUD 功能,然后创建一个名为“UnitOfWork
”的文件夹并创建一个名为“UnitOfWork.cs”的类。您应该在“UnitOfWork.cs”中编写每个实体的 Repository 列表,此外还有“Save()
”和“Dispose()
”方法。控制器只能访问 UnitOfWork
。因此,您将业务层与数据层分离,并且每当您想更改策略并倾向于使用其他 ORM(如 NHibernate)时,您就不会在业务层等高层遇到任何麻烦。
为什么要在 Entity Framework 中使用 Repository
这是一个很好的问题:如果我们使用 Entity Framework,为什么还需要在 Data Context 之上建立另一个 Repository?因为 Data Context 本身就是一个 Repository。想象一下,有一天,您想在数据访问层中使用其他方法,如 NHibernate、ADO.NET 甚至 XML 文件,或者假设您必须将数据库从 SQL 更改为 Oracle,那么您的麻烦就非常小,您只需要稍微更改您的代码,而不是更改几乎整个结构并重写它。因此,Repository Pattern 使我们能够正确地解耦各层,并在我们将来更改部分(尤其是数据层)时派上用场。另一方面,测试也会更容易。
什么是 AngularJS
AngularJS 是一个 JavaScript 框架,用于以更结构化、清晰、简洁的方式组织 HTML 代码。这种客户端技术提供了简单轻便的代码,从而使开发甚至设计变得简单。AngularJS 消除了大多数冗余代码,特别是在 CRUD Web 应用程序中。它是一个 MV(无论你喜欢什么)模式,不仅仅是 MVC。
有两种配件可以帮助我们在用户界面和业务核心及数据层之间建立桥梁。
- 库:这些类型是一组函数,例如 JQuery,当您使用其中一些函数(
$.ajax
)时,它将调用相关函数来处理函数。 - 框架:这些类型是实现应用程序的特定结构,开发人员必须遵循这些结构,例如 durandal 和 ember。
AngularJS 具有不同的工作方式来满足我们的需求,Angular 将新属性嵌入到 HTML 标签中,例如“ng-model
”、“ng-repeat
”,它们被称为指令,以便消除我们匹配和转换数据的障碍。
另一方面,AngularJS 以良好的结构将 Ajax 和 HTML DOM 融合在一起,我将在下面更详细地介绍。
Angular 的优势
- 它非常适合 CRUD Web 应用程序。
- 它使 CRUD Web 应用程序的测试变得容易。
- 您需要编写更少的代码。
- 您可以更快地运行您的代码。
- AngularJS 中最受欢迎和最著名的功能之一是双向简单绑定。
<input type="text" ng-model="simpleBinding" /><span>{{simpleBinding}}</span>
- 您无需修改 HTML DOM。
- 借助指令,您的任务更加轻松省时。
- 通过其 MVC 架构或更准确地说 MVW,解耦是真实的且优秀的。
设计指南
如上图所示,您应该从 https://angularjs.org/ 下载 Angular 文件,并将 jquery 和 Angular js 文件放入 script 文件夹中。在 Module.js 中,为 angular 应用命名,例如“MyApp
” - 这个名字将您的 Angular 文件相互关联,您应该在您的视图的 html
标签中使用它,在此场景中,我使用了“_Layout.cshtml”作为我的主视图(根据 MVC Pattern),在此 html
标签中,您应该编写一个指令 angular ng-app='MyApp'
,它包含了 Angular 文件。
然后您必须通过 <script src=?>
将这些文件引入您的视图。
Index.cshtml 继承自 _Layout.cshtml,现在通过在 div
中添加另一个指令 ng-controller='angularCtrl'
,您可以在视图和 controller.js 之间建立关联,因为 angularCtrl
是 Controller.js 的名称。
您只需要使用一个简单的 HTML 标签,例如 <input type='text'>
,并为该 input
标签添加 ng-model='empid'
指令,每当您想从 Controller.js 引用此输入(设置或获取数据)时,通过 $Scope.empid
调用它。
同样的故事也适用于 <input type='button'>
,并为该 input
标签添加 ng-click='add()'
指令,每当您想从 Controller.js 引用此输入(设置或获取数据)时,通过 $Scope.add()
调用它。
要在 Angular 中在表格中表示数据,您可以使用简单的 table
标签,通过 ng-repeat="employee in employees"
,现在每当您想(设置或获取数据)从 Controller.js 中,您只需要使用:$Scope.employees
并使用表达式,例如 {{employee.ID}}
或 {{employee.FirstName}}
或其他字段。
<table>
<tr ng-repeat="employee in employees">
<td>
{{employee.ID}}
</td>
</tr>
</table>
如果您想在 controller.js 中编写函数,您应该调用 ServiceName.FunctionName
,例如 angularservice.getEmp(), "angularservice"
是 Service.js 的名称。现在在“Service.js”中,您可以继续函数 { "getEmp()" }
使用 $http.get("/ControllerName/ActionName")
,或者对于用于将数据从视图传递到控制器的 adding
函数,请使用
在 Controller.js 中将数据传递给服务。
var Employee = {
FirstName: $scope.FirstName ,
LastName: $scope.LastName ,
UserName: $scope.UserName
};
angularService.Add(Employee)
在 Service.js 中将数据传递给 EmployeeController.cs。
this.Add = function (employee) {
var response = $http({
method: "post",
url: "/Employee/Add",
data: JSON.stringify(employee),
dataType: "json"
});
return response;
}
Angularjs vs Jquery
Jquery 中的障碍和 AngularJS 中的解决方案
- Jquery 问题:如果要使用多个实体,则不允许在单个视图中使用多个模型,因此您必须编写
viewmodel
来支持它。AngularJS 解决方案:您可以使用
$Scope
对象来处理。这个小巧而强大的对象可以提供数据并进行更改。 - Jquery 问题:如果您要使用
viewmodel
,则在使用foreach
循环时会遇到问题,因此您必须使用for
循环。AngularJS 解决方案:您可以使用
table
{tr
标签} 中的ng-repeat
指令来解决它。 - Jquery 问题:您必须操作 HTML DOM 并根据模型架构自定义您的需求,并编写类似以下内容:
Html.EditorFor(model => model.ArticleTitle)
AngularJS 解决方案:但是借助 AngularJS,您可以使用
<input>
,只需添加特定指令,即可达到目标。
如何组织 AngularJS 文件
Dispose Pattern (释放模式)
要了解 Dispose
模式,有必要了解垃圾回收。
垃圾回收
当您从数据类型创建对象时,公共语言运行时 (CLR) 会为您的新对象在内存中分配特定空间,在此过程中,托管堆帮助 CLR 将对象分配到内存。内存空间是有限的,不可能像消费者那样多的对象使用资源。实际上,我们需要一个工具来释放不再长时间使用且应用程序已有一段时间未调用的对象的内存。垃圾收集器是管理内存并释放旧的、无用对象的空间的合适工具。
IDisposable
是一个接口,用于释放资源的特定回收,这些资源的生命周期对程序员来说是已知的。它的优点是高速分配服务,没有长期碎片化问题。
在下面的图片中,您可以看到三个阶段,第一个阶段,“A”、“B”、“C”这些名称的对象已占用资源,正如您所看到的,“A”和“B”已死,而“C”是活动的,另一方面,我们的新对象“D”、“E”和“F”在队列中等待使用资源。假设没有工具来停止和释放内存或资源,那么其他对象必须在队列中等待很长时间,性能会下降。垃圾收集器在此处提供帮助,收集“A”和“B”并将它们从资源中移除,因为它们已经过时且长期没有应用程序使用它们。因此,在第二阶段,我们有更多的可用空间,“D”、“E”和“F”将进入第三阶段。Dispose 方法或更准确地说“Dispose Pattern”有助于我们提高性能,尤其是在我们知道资源(上下文)生命周期的情况下。
class X: IDisposable
{
//Define Flag: Show us if dispose has been called or not
bool disposed = false;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
//Using SuppressFinalize helps us to do not finalize object later
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern and allow to override it later
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing) {
//Free any other managed objects here.
context.Dispose();
}
// Free any unmanaged objects here.
disposed = true;
}
~X()
{
// release resources
Dispose(false);
}
};
//Calling dispose inside Controller:
protected override void Dispose(bool disposing)
{
X.Dispose();
base.Dispose(disposing);
}
如何安装 AngularJS
转到 -> 工具菜单 -> 程序包管理器 -> 程序包管理器控制台
在命令行中输入:Install-Package angularjs -Version 1.3.8
请注意 Angular 的不同版本,因为它可能需要略有不同的代码样式。
Using the Code
场景
我想遵循权限管理场景来更好地解释这些概念(AngularJS 和 MVC 中的 Repository)。它包括两个页面,第一个页面执行 CRUD 功能,创建员工,读取或选择员工,更新和删除他们的信息,此外,它还提到了 Angular 的其他功能,如路由、过滤。第二个页面为每个员工分配权限,您需要一个组合框来保存员工姓名和权限角色。因此,它涵盖了拥有健壮 MVC Web 应用程序的基本要求。
- Employee CRUD(创建、读取、更新、删除):此页面显示数据,用户可以编辑、删除或添加新的
employee
。 - AngularJS 能够过滤数据
- 当用户点击“编辑”按钮时 ->“更新员工”部分会出现。
- 当用户点击“添加”按钮时 ->“添加员工”部分会出现。最后,通过点击“权限”链接,Angular 会通过路由功能将您引导至权限页面。
- 用户可以通过从
combobox
中选择员工姓名来为特定employee
分配权限。 - 将数据加载到
combobox
中。
在 MVC 项目中使用 Repository 和 AngularJS 的分步指南
(烹饪书式说明)
- 创建数据库并命名为“
MVCAdvanced
”。 - 创建两个表:“
Employee
”和“EmpRole
”。 - 创建新的 MVC 项目。
- 创建新的数据模型。
- 在解决方案中创建新文件夹并命名为“
GenericRepository
”。 - 创建“GenericRepository.cs”类。
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; namespace MvcAdvanced.GenericRepository { public class GenericRepository<tentity> where TEntity : class { internal MvcAdvancedEntities context; internal DbSet<tentity> dbSet; public GenericRepository(MvcAdvancedEntities context) { this.context = context; this.dbSet = context.Set<tentity>(); } public virtual IEnumerable<tentity> Get() { IQueryable<tentity> query = dbSet; return query.ToList(); } public virtual TEntity GetByID(object id) { return dbSet.Find(id); } public virtual void Insert(TEntity entity) { dbSet.Add(entity); } public virtual void Delete(object id) { TEntity entityToDelete = dbSet.Find(id); Delete(entityToDelete); } public virtual void Delete(TEntity entityToDelete) { if (context.Entry(entityToDelete).State == EntityState.Detached) { dbSet.Attach(entityToDelete); } dbSet.Remove(entityToDelete); } public virtual void Update(TEntity entityToUpdate) { dbSet.Attach(entityToUpdate); context.Entry(entityToUpdate).State = EntityState.Modified; } } }
- 创建“
UnitOfWork
”文件夹并创建一个类“UnitOfWork.cs”。using System; using System.Collections.Generic; using System.Linq; using System.Web; using MvcAdvanced.GenericRepository; namespace MvcAdvanced.UnitOfWork { public class UnitOfWork : IDisposable { private MvcAdvancedEntities context = new MvcAdvancedEntities(); private GenericRepository<employee> employeeRepository; private GenericRepository<emprole> empRoleRepository; public GenericRepository<employee> EmployeeRepository { get { if (this.employeeRepository == null) this.employeeRepository = new GenericRepository<employee>(context); return employeeRepository; } } public GenericRepository<emprole> EmpRoleRepository { get { if (this.empRoleRepository == null) this.empRoleRepository = new GenericRepository<emprole>(context); return empRoleRepository; } } public void Save() { context.SaveChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { //Free any other managed objects here. context.Dispose(); } // Free any unmanaged objects here. disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
- 在“Controller”文件夹中创建“
EmployeeController
”。using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcAdvanced.GenericRepository; using AutoMapper; namespace MvcAdvanced.Controllers { public class EmployeeController : Controller { private UnitOfWork.UnitOfWork unitOfWork = new UnitOfWork.UnitOfWork(); public ActionResult Index() { return View(); } public JsonResult GetAllEmployees() { var employeeList = (List<employee>)unitOfWork.EmployeeRepository.Get(); return Json(employeeList, JsonRequestBehavior.AllowGet); } public string Update(Employee employee) { if (employee != null) { var emp = unitOfWork.EmployeeRepository.GetByID(employee.ID); emp.FirstName = employee.FirstName; emp.LastName = employee.LastName; emp.UserName = employee.UserName; unitOfWork.EmployeeRepository.Update(emp); unitOfWork.Save(); return "Record has been Updated"; } else { return "Record has Not been Updated"; } } public string Delete(int id) { try { if (id != null) { unitOfWork.EmployeeRepository.Delete(id); unitOfWork.Save(); return "Employee Has Been Deleted"; } else { return "Employee Hasnot Been Deleted"; } } catch { return "Employee Hasnot Been Deleted"; } } public string Add(Employee employee) { try { if (employee != null) { unitOfWork.EmployeeRepository.Insert(employee); unitOfWork.Save(); return "Record has been Added"; } else { return "Record has Not been Verified"; } } catch { return "Record has Not been Added"; } } protected override void Dispose(bool disposing) { unitOfWork.Dispose(); base.Dispose(disposing); } } }
- 在“
Controller
”类中创建“PermissionController
”。using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcAdvanced.GenericRepository; namespace MvcAdvanced.Controllers { public class PermissionController : Controller { private UnitOfWork.UnitOfWork unitOfWork = new UnitOfWork.UnitOfWork(); public ActionResult Index() { return View(); } public JsonResult GetAllEmpRole() { var employeeList = unitOfWork.EmpRoleRepository.Get(); return Json(employeeList, JsonRequestBehavior.AllowGet); } public JsonResult GetAllEmpNames() { var employeeList = unitOfWork.EmployeeRepository.Get(); return Json(employeeList, JsonRequestBehavior.AllowGet); } public JsonResult GetAllRoles() { var roleList = (from emp in unitOfWork.EmployeeRepository.Get() join role in unitOfWork.EmpRoleRepository.Get() on emp.RoleID equals role.ID select new { emp.ID, emp.FirstName, emp.LastName, emp.UserName, role.Role }).ToList(); return Json(roleList, JsonRequestBehavior.AllowGet); } public string UpdateRole(Employee permission) { if (permission != null) { var emp = unitOfWork.EmployeeRepository.GetByID(permission.ID); emp.RoleID = permission.RoleID; unitOfWork.EmployeeRepository.Update(emp); unitOfWork.Save(); return "Record has been Updated"; } else { return "Record has Not been Updated"; } } protected override void Dispose(bool disposing) { unitOfWork.Dispose(); base.Dispose(disposing); } } }
- 从以下网址下载 angularjs:
我使用了 angularjs 版本 1.3.8。版本之间可能会有一些(代码样式)更改。将 angular.js 和 angular-route.js 放入“Scripts”文件夹。
- 创建 Angular 文件
在“Content”文件夹中,新建一个文件夹并命名为“Angular”,然后在其中创建三个 JavaScript 文件并命名为:
{ Module.js, Controller.js, Service.js }
。 - 在 Module.js 中,写入:
var app = angular.module('MyApp', ['ngRoute']); app.config(['$routeProvider',function ($routeprovider) { $routeprovider. when('/employee', { templateurl: '/Views/Employee/index.cshtml', controller: 'AngularCtrl' }). when('/permission', { templateurl: '/Views/Permission/index.cshtml', controller: 'AngularCtrlRole' }). otherwise({ redirectto: '/employee' }); }]);
- 在 Views -> Shared -> _Layout.cshtml, 中写入:(您通过添加
ng-app
将您的应用程序名称“MyApp
”引入您的视图)<!DOCTYPE html> <html ng-app='MyApp'> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> <script src="~/Scripts/angular.js"></script> <script src="~/Scripts/angular.min.js"></script> <script src="~/Scripts/angular-route.js"></script> <script src="~/Content/Angular/Module.js"></script> <script src="~/Content/Angular/Service.js"></script> <script src="~/Content/Angular/Controller.js"></script> @Styles.Render("~/Content/css") </head> <body> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
- 在 Views -> Employee -> Index.cshtml 中写入:
@{ ViewBag.Title = "Index"; } <h2>Index</h2> <div ng-controller="AngularCtrl"> <a href="/permission">Permission</a><br /> Filter: <input type="text" value="Name" ng-model="FilterByFirstName" /> <br /> <br /> <input type="button" value="Add" ng-click="add()" /> <table cellpadding="12"> <tr> <td><b>ID</b></td> <td><b>FirstName</b></td> <td><b>LastName</b></td> <td><b>UserName</b></td> <td><b>Operation</b></td> </tr> <tr ng-repeat="employee in employees | filter:FilterByFirstName "> <td> {{employee.ID}} </td> <td> {{employee.FirstName}} </td> <td> {{employee.LastName}} </td> <td> {{employee.UserName}} </td> <td> <input type="button" value="Edit" ng-click="edit(employee)" /> <input type="button" value="Delete" ng-click="delete(employee)" /> </td> </tr> </table> <div ng-show="divEmpModification"> <p>{{Operation}} Employee</p> <table> <tr> <td> <input type="text" style="width:20px;" disabled="disabled" ng-model="ID" /> </td> <td> <input type="text" style="width:94px;" ng-model="FirstName" /> </td> <td> <input type="text" style="width:94px;" ng-model="LastName" /> </td> <td> <input type="text" style="width:94px;" ng-model="UserName" /> </td> <td colspan="2"> <input type="button" value="Save" ng-click="Save()" /> </td> </tr> </table> </div> </div>
- 在 Views -> Permission -> Index.cshtml 中写入:
@{ ViewBag.Title = "Index"; } <h2>Index</h2> <div ng-controller="AngularCtrlRole"> <a href="/employee">Employee</a> <p ng-model="mahsa"> ID of selected LastName is : {{selectedItem.ID}} </p> <select data-ng-Model="selectedItem" ng-options="item.LastName for item in items"> </select> <p> ID of selected Role is : {{selectedItemRole.ID}} </p> <select ng-model="selectedItemRole" ng-options="roleitem.Role for roleitem in roleitems"> </select> <input type="button" value="Save Permission" ng-click="SavePermission()" /> <table cellpadding="12"> <tr> <td><b>ID</b></td> <td><b>First Name</b></td> <td><b>Last Name</b></td> <td><b>User Name</b></td> <td><b>Role Name</b></td> </tr> <tr ng-repeat="view in views "> <td> {{view.ID}} </td> <td> {{view.FirstName}} </td> <td> {{view.LastName}} </td> <td> {{view.UserName}} </td> <td> {{view.Role}} </td> </tr> </table> </div>
- 在 Content -> Angular -> Controller.js 中写入:
app.controller("AngularCtrl", function ($scope, angularService) { $scope.divEmpModification = false; GetAll(); //To Get All Records function GetAll() { var Data = angularService.getEmp(); Data.then(function (emp) { $scope.employees = emp.data; }, function () { alert('Error'); }); } $scope.edit = function (employee) { $scope.ID = employee.ID; $scope.FirstName = employee.FirstName; $scope.LastName = employee.LastName; $scope.UserName = employee.UserName; $scope.Password = employee.Password; $scope.Operation = "Update"; $scope.divEmpModification = true; } $scope.add = function () { $scope.ID =""; $scope.FirstName = ""; $scope.LastName = ""; $scope.UserName = ""; $scope.Password = ""; $scope.Operation = "Add"; $scope.divEmpModification = true; } $scope.Save = function () { var Employee = { FirstName: $scope.FirstName , LastName: $scope.LastName , UserName: $scope.UserName, Password: $scope.Password }; var Operation = $scope.Operation; if (Operation == "Update") { Employee.ID = $scope.ID; var getMSG = angularService.update(Employee); getMSG.then(function (messagefromController) { GetAll(); alert(messagefromController.data); $scope.divEmpModification = false; }, function () { alert('Update Error'); }); } else { var getMSG = angularService.Add(Employee); getMSG.then(function (messagefromController) { GetAll(); alert(messagefromController.data); $scope.divEmpModification = false; }, function () { alert('Insert Error'); }); } } $scope.delete = function (employee) { var getMSG = angularService.Delete(employee.ID); getMSG.then(function (messagefromController) { GetAll(); alert(messagefromController.data); }, function () { alert('Delete Error'); }); } }); app.controller("AngularCtrlRole", function ($scope, angularServiceRole) { GetAllNames(); GetAllRoles(); GetAllEmpRole(); //To Get All Records function GetAllEmpRole() { var Data = angularServiceRole.getEmpRole(); Data.then(function (emp) { $scope.views = emp.data; }, function () { alert('Error'); }); } //To Get All Records function GetAllNames() { var Data = angularServiceRole.getName(); Data.then(function (emp) { $scope.items = emp.data; }, function () { alert('Error'); }); } function GetAllRoles() { var Data = angularServiceRole.getRole(); Data.then(function (role) { $scope.roleitems = role.data; }, function () { alert('Error'); }); } $scope.SavePermission = function () { var Permission = { ID: $scope.selectedItem.ID, RoleID: $scope.selectedItemRole.ID }; var getMSG = angularServiceRole.updateRole(Permission); getMSG.then(function (messagefromController) { GetAllNames(); GetAllRoles(); GetAllEmpRole(); alert(messagefromController.data); }, function () { alert('Save Permission Error'); }); } });
- 在 Service.js 中,写入:
app.service("angularService", function ($http) { this.getEmp = function () { return $http.get("/Employee/GetAllEmployees"); }; //Save (Update) this.update = function (employee) { var response = $http({ method: "post", url: "/Employee/Update", data: JSON.stringify(employee), dataType: "json" }); return response; } //Delete this.Delete = function (empID) { var response = $http({ method: "post", url: "/Employee/Delete", params: { id: empID } }); return response; } //Add this.Add = function (employee) { var response = $http({ method: "post", url: "/Employee/Add", data: JSON.stringify(employee), dataType: "json" }); return response; } }); app.service("angularServiceRole", function ($http) { this.getEmpRole = function () { return $http.get("/Permission/GetAllEmpRole"); }; this.getName = function () { return $http.get("/Permission/GetAllEmpNames"); }; this.getRole = function () { return $http.get("/Permission/GetAllRoles"); }; //Save Permission this.updateRole = function (permission) { var response = $http({ method: "post", url: "/Permission/UpdateRole", data: JSON.stringify(permission), dataType: "json" }); return response; } });
参考文献
- https://msdn.microsoft.com/en-us/library/ff649690.aspx
- http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and-entity-framework.htm
- https://docs.angularjs.org/guide/introduction
- https://www.youtube.com/watch?v=i9MHigUZKEM&feature=youtu.be
- http://aspnetscript.com/mvc/learn-angularjs-mvc/
历史
- 2015/1/26:第一个版本
- 2015/1/29:第二个版本:为实体创建一个 Repository。
- 2015/2/15:第三个版本:带
GenericRepository
和UnitOfWork
的 Repository Pattern + 图解说明。
反馈
请随时对本文提供任何反馈;很高兴看到您的评论和投票。如果您有任何问题,请随时在此处提问。