AngularJS MVC 存储库释放






4.82/5 (97投票s)
这是关于 AngularJS 和存储库模式最简单的教程,用于开发专业的 MVC 应用程序。它包含一个关于实际权限管理项目的源代码。
引言
本文旨在阐明 AngularJS 技术和 存储库,后者是用于轻松、专业地开发 Web 应用程序的有用设计模式之一。Jquery 存在一些根本性困难,例如代码混乱或陷入死锁,但 AngularJS 能够解决 Jquery 的一些障碍。AngularJS 功能强大,尤其适用于 CRUD(创建、读取、更新和删除)Web 应用程序,它遵循 MVC 模式,因此我们的代码整洁清晰。此外,它使我们能够编写更少的代码,并且在 AngularJS 中进行测试代码的条件更好。尽管这些因素并不能减弱 Jquery 在编写游戏等其他类型应用程序方面的强大功能。
本文的另一个重点是解释存储库模式,该模式封装了数据访问层,并在实际数据库与其他数据访问层部分之间划清界限。它具有一些对开发人员有利的优点,例如,它使得更改和更新数据上下文更加方便,并且测试框架不必运行物理数据访问代码,因此这种隔离使其更具灵活性。
最后但同样重要的是,为初学者讲解如何在 Web 浏览器中调试脚本。
我将更广泛地描述每个部分,我将在一个实际项目中打开这些技术和模式,以便对它们有一个清晰的概念。
背景
什么是存储库
存储库是一种有用的设计模式,它隐藏了物理数据,不让其他数据访问层部分访问。专业地说,存储库为我们提供了有关如何从其他数据库查询和数据访问逻辑中封装数据上下文的说明。它就像一条线,将实际数据库与其他部分隔离开来,最终使我们的 Web 应用程序更方便地进行分层测试。此外,它还提供了一个类似内存的集合 https://codeproject.org.cn/Articles/832189/List-vs-IEnumerable-vs-IQueryable-vs-ICollection-v,用于访问领域对象,这些对象忽略了持久化并提高了性能。因此,我们倾向于在 MVC 应用程序中使用存储库来实现可测试性、速度和未来更改的灵活性。
我们有两种存储库结构选择。一种是为每个实体构建一个 Repository
类和一个 IRepository
接口,另一种方法是为所有实体创建一个 GenericRepository
类,并定义基本的 CRUD(创建、读取、更新、删除)操作以及一个 UnitOfWork
类,以便每个实体的所有存储库都应基于 UnitOfWork
类构建。毫无疑问,当实体数量过多时,第二种方法是可取的。
正如我们在 MVC 中为每个实体创建一个控制器,命名为“XController
”一样,我们创建一个文件夹并命名为 *GenericRepository*,然后创建一个类“*GenericRepository.cs*”。“*GenericRepository.cs*”类具有处理数据上下文的 CRUD 函数,然后创建一个文件夹并命名为“UnitOfWork
”,然后创建一个类“*UnitOfWork.cs*”。您应该在“*UnitOfWork.cs*”中为每个实体编写存储库列表,此外还编写“Save()
”和“Dispose()
”方法。控制器只访问 UnitOfWork
。因此,您将业务层与数据层分开,并且无论何时您想更改策略并偏好使用其他 ORM,例如 NHibernate,您都不会在业务层等高层遇到任何麻烦。
为什么在 Entity Framework 中使用存储库
这是一个好问题,如果我们使用 Entity Framework,为什么还需要在 Data Context 之上建立另一个存储库?因为 Data Context 本身就是存储库。想象一下,有一天,您想在数据访问层中使用其他方法,例如 NHibernate、ADO.NET 甚至 XML 文件,或者假设您必须将数据库从 SQL 更改为 Oracle,那么您的麻烦会很小,您只需更改代码中的一小部分,而不是更改几乎整个结构并重新编写。因此,存储库模式使我们能够正确解耦层,并在未来更改我们的部分(尤其是数据层)时非常方便。另一方面,测试也会变得容易。
什么是 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 模式),在 html
标签中,您应该编写一个指令 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")
,或者对于用于将数据从视图传递到控制器的添加函数,请使用
在 *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 问题:您应该在 HTM DOM 上进行操作,并根据您的模型架构自定义您的需求,并编写类似以下内容:
Html.EditorFor(model => model.ArticleTitle)
AngularJS 解决方案:但是借助 AngularJS,您可以使用
<input>
,只需添加特定指令,您就可以达到目标。
如何组织 AngularJS 文件
Dispose 模式
要了解 Dispose
模式,有必要了解垃圾回收。
垃圾回收
当您从数据类型创建对象时,公共语言运行时 (CRL) 会为您的新对象在内存中分配特定空间,在此过程中,托管堆帮助 CLR 将对象分配到内存中。内存空间是有限的,不可能像消费者一样多的对象使用资源。事实上,我们需要一种工具来释放不再长时间使用的对象占用的内存,并且应用程序在一段时间内没有调用它们。垃圾收集器是管理内存并释放旧对象和无用对象空间的合适工具。
IDisposable
是一个接口,用于释放特定重用资源的资源,这些资源的生命周期对程序员来说是已知的。它的优点是高速分配服务,没有长期碎片问题。
在下图所示的三个阶段中,第一个阶段的对象名称为“A”、“B”、“C”,它们已经占用了资源,正如显而易见的那样,“A”和“B”是已死的,而“C”是活着的,另一方面,我们的新对象“D”、“E”和“F”正在等待使用资源。假设没有工具来停止和释放内存或资源,那么其他对象必须在队列中等待很长时间,性能会下降。垃圾收集器在这里提供帮助,收集“A”和“B”并将它们从资源中移除,因为它们很旧,并且长时间没有应用程序使用它们。因此,在第二阶段,我们有了更多的可用空间,“D”、“E”和“F”将在第三阶段进入。Dispose 方法,或者说“Dispose 模式”,有助于我们提高性能,尤其是在我们知道资源(上下文)的生命周期时。
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
场景
我想遵循权限管理场景来更好地解释这些概念(MVC 中的 AngularJS 和存储库)。它包括两个页面,第一个页面执行 CRUD 功能,创建员工,读取或选择员工,更新和删除他们的信息,此外,它还提到了 Angular 的其他功能,如路由、过滤。第二个页面为每个员工分配权限,这里您需要一个组合框来保存员工姓名和权限角色。因此,它涵盖了拥有健壮的 MVC Web 应用程序的基本要求。
- 员工 CRUD(创建、读取、更新、删除):此页面显示数据,用户可以编辑、删除或添加新的
employee
。 - AngularJS 能够过滤数据
- 当用户点击“编辑”按钮时 -> “更新员工”部分出现。
- 当用户点击“添加”按钮时 -> “添加员工”部分出现。最后,通过点击“权限”链接,Angular 会通过路由功能引导您到权限页面。
- 用户可以通过从
combobox
中选择其姓名来为特定employee
分配权限。 - 将数据加载到
combobox
中
在您的 MVC 项目中使用存储库和 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/01/26:第一个版本
- 2015/01/29:第二个版本:为实体创建一个存储库
- 2015/02/15:第三个版本:具有
GenericRepository
和UnitOfWork
的存储库模式 + 图形解释
反馈
请随时对本文提供任何反馈;很高兴看到您的评论和投票。如果您有任何问题,请随时在此处提问。