AngularJS 在 MVC 中实现 CRUD、分页、排序、搜索






4.96/5 (12投票s)
本文首先介绍了在 MVC 中创建项目,并使用 Bootstrap 类来美化 UI 和 UI 控件。
引言
在选择最新技术时,需要考虑多种因素,包括这些技术将如何集成到我们的项目中。本文为初学者解决了使用 AngularJS 和 MVC 工作的问题。本文详细介绍了 AngularJS 的使用方式、原因和方法。
开始数据库操作
- 首先,创建一个名为 TestData 的数据库。
- 创建数据库后,创建一个名为 Employee、Designation 和 Department 的表。
- 将 Id 列设置为主键并自增。
- 数据库操作至此完成。
从下面提供的链接下载所需的 JS 和 CSS 文件。
在继续之前,请熟悉以下概念。
- 模块用于分隔应用程序的逻辑。
- var app = angular.module("myApp", ['angularUtils.directives.dirPagination']);
- 在此代码中,我们使用 angular.module 声明应用程序的 myApp 模块。在数组中,我们传入依赖的模块,例如在此我们传入了用于分页的依赖模块。
- 我们在 HTML 页面中使用 ng-app 指令来使用该模块。
- AngularJS 主要依赖于控制器来控制数据及其流程。
- 每次页面加载时,Controller.js 文件也会加载,并且会执行在加载时调用的方法。
- 控制器包含包含函数、方法和属性的 JavaScript 对象。
- 每个控制器都接受 $scope 作为参数,它引用应用程序。
- 我们在 HTML 页面中使用 ng-controller 来使用控制器。
- 服务是执行控制器指示的特定任务的 JavaScript 函数。AngularJS 有许多内置服务,如 $http、$location、$route、$window。每个服务都会执行特定任务。例如:$http 用于向服务器发出 AJAX 请求。
- 控制器中的方法调用服务中的方法。
- 服务处理服务器代码,调用 AJAX URL 中指定的ActionResult,并将响应返回给服务。
- 服务然后将响应返回给 controller.js,controller.js 处理视图并在页面上显示数据。
开始编写代码。
- 打开 VS2012,创建一个新的 ASP.Net MVC4 Web 应用程序,并命名为 BootstrapAngularMvc。
- 在 Visual Studio 的解决方案资源管理器中,转到 Models 文件夹。
- 右键单击 Models 文件夹,找到 ADD > ADO.NET Entity Data Model。选择 ADO.NET Entity Data Model。
- 将名称命名为 DBModel。之后会弹出窗口。
- 选择“从数据库生成”并单击“下一步”。
- 在下面的框中输入实体名称 SahilEntities,然后单击“新建连接”。
- 选择 SQL Server 身份验证,填写服务器名称、用户名、密码等凭据,然后从数据库列表中选择您的 TestData 数据库。
- 勾选表复选框,然后单击“完成”。
- 之后,转到 controller 文件夹并创建 EmployeeController。然后编写代码。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BootstrapAngularMvc.Models; namespace BootstrapAngularMvc.Controllers { public class EmployeeController : Controller { public ActionResult Employee() { return View(); } //For getting the all records from database. public JsonResult getAll() { using (SahilEntities dataContext = new SahilEntities()) { var employeeList = (from E in dataContext.Employees join dep in dataContext.Departments on E.DepartmentID equals dep.Id join dsg in dataContext.Designations on E.DesignationID equals dsg.Id orderby E.Id select new { E.Id, E.name, E.DOB, E.Gender, E.Email, E.Mobile, E.Address, E.JoiningDate, dep.DepartmentName, E.DepartmentID, dsg.DesignationName, E.DesignationID }).ToList(); var JsonResult = Json(employeeList, JsonRequestBehavior.AllowGet); JsonResult.MaxJsonLength = int.MaxValue; return JsonResult; } } } }
- 在 App_Start 文件夹中找到 RouteConfig.cs,并更改默认的 Controller 和 Action。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace BootstrapAngularMvc { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Employee", action = "Employee", id = UrlParameter.Optional } ); } } }
- 在 content 文件夹中添加 3 个文件 --> Module.js, Controller.js, Service.js。
In Module.js write the given code.
var app = angular.module("myApp", []);
In Controller.js write the given code . app.controller("myCntrl", function ($scope, myService) { GetAllEmployees(); //For sorting according to columns $scope.sort = function (keyname) { $scope.sortKey = keyname; $scope.reverse = !$scope.reverse; } //To Get All Records function GetAllEmployees() { var getData = myService.getEmployees(); getData.then(function (emp) { $scope.employees = emp.data; }, function (emp) { alert("Records gathering failed!"); }); } });
In Service.js write the given code. app.service("myService", function ($http) { //get All Employee this.getEmployees = function () { return $http.get("/Employee/getAll"); }; });
- 右键单击 EmployeeController 的 Employee Action,然后选择“添加视图”选项。
- 添加一个视图,并查看下面提供的链接中的代码。
开始分页
- 下载 DirPagination.js 并保存在项目的 content 文件夹中。
- 更新 Module.js 中的代码。
var app = angular.module("myApp", ['angularUtils.directives.dirPagination']);
更改 CSS
- 在 content 文件夹中找到 site.css,并将 main content 中的 html、body、body 的背景颜色更改为 "#fff"。
开始使用 AngularJS 进行 CRUD 操作
- 在 Employee Controller 中添加代码。
- 下方代码中的第一个方法使用 Employee 类作为参数,以通过 controller.js 从视图获取数据。
- 第二个方法使用 EmployeeID 作为参数,该参数来自被单击的行。
- 再次更新方法也接受 Employee 类作为参数,并更新已编辑的记录。
- 另外 2 个方法用于填充下拉列表中的职位和部门。
<-- Employee record insertion code --> public string AddEmployee(Employee Emp) { if (Emp != null) { using (SahilEntities dataContext = new SahilEntities()) { Employee employee = new Employee(); employee.name = Emp.name; employee.DOB = Convert.ToDateTime(Emp.DOB).ToString("yyyy/MM/dd"); employee.Gender = Emp.Gender; employee.Email = Emp.Email; employee.Mobile = Emp.Mobile; employee.Address = Emp.Address; employee.JoiningDate = Convert.ToDateTime(Emp.JoiningDate).ToString("yyyy/MM/dd"); employee.DepartmentID = Emp.DepartmentID; employee.DesignationID = Emp.DesignationID; dataContext.Employees.Add(employee); dataContext.SaveChanges(); return "Employee added Successfully"; } } else { return "Addition of Employee unsucessfull !"; } } <-- Get Employee by ID --> public JsonResult getEmployeeByNo(string EmpNo) { try { using (SahilEntities dataContext = new SahilEntities()) { int no = Convert.ToInt32(EmpNo); var employeeList = dataContext.Employees.Find(no); return Json(employeeList, JsonRequestBehavior.AllowGet); } } catch (Exception exp) { return Json("Error in getting record !", JsonRequestBehavior.AllowGet); } } <-- Employee record updation code --> public string UpdateEmployee(Employee Emp) { if (Emp != null) { using (SahilEntities dataContext = new SahilEntities()) { int no = Convert.ToInt32(Emp.Id); var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault(); employeeList.name = Emp.name; employeeList.DOB = Convert.ToDateTime(Emp.DOB).ToString("yyyy/MM/dd"); employeeList.Gender = Emp.Gender; employeeList.Email = Emp.Email; employeeList.Mobile = Emp.Mobile; employeeList.Address = Emp.Address; employeeList.JoiningDate = Convert.ToDateTime(Emp.JoiningDate).ToString("yyyy/MM/dd"); employeeList.DepartmentID = Emp.DepartmentID; employeeList.DesignationID = Emp.DesignationID; dataContext.SaveChanges(); return "Employee Updated Successfully"; } } else { return "Invalid Employee"; } } <-- Bind dropdownlist of designations --> public JsonResult GetDesignations() { using (SahilEntities context = new SahilEntities()) { var desg = context.Designations.ToList(); return Json(desg, JsonRequestBehavior.AllowGet); } } <-- Bind dropdownlist of departments --> public JsonResult GetDepartments() { using (SahilEntities data = new SahilEntities()) { var deps = data.Departments.ToList(); return Json(deps, JsonRequestBehavior.AllowGet); } }
- 在 Controller.js 中编写代码,即如下所示。
- 在控制器中,$scope 用于连接控制器和视图。它是应用程序控制器和视图之间的粘合剂。在控制器中,我们将值传递给 $scope,并在视图中使用 ng-bind 或 {{}}。
- AddEmployeeDiv 打开用于添加员工的模态弹出窗口,并填充职位和部门的下拉列表。
- alertmsg 在数据保存或更新或保存操作期间发生任何错误后显示消息。
- EditEmployee 方法调用服务中的方法来编辑记录。
- 基于编辑或添加的操作,AddUpdateEmployee 方法调用服务中的方法来进行员工的插入或删除。
- ClearFields 方法用于在任何操作后清空文本框。
<-- This is used to open popup for adding record. --> $scope.AddEmployeeDiv = function () { ClearFields(); $scope.Action = "Add"; GetDepartments(); GetDesignations(); } <-- Alert Popup for save ,update messages . --> $scope.alertmsg = function () { $("#alertModal").modal('hide'); }; <-- Bind dropdownlist for designation. --> function GetDesignations() { var desg = myService.GetDesignations(); desg.then(function (dsg) { $scope.designations = dsg.data; }, function (dsg) { $("#alertModal").modal('show'); $scope.msg = "Error in filling designation drop down !"; }); } <-- Bind dropdownlist for department. --> function GetDepartments() { var departments = myService.GetDepartment(); departments.then(function (dep) { $scope.departments = dep.data; }, function (dep) { $("#alertModal").modal('show'); $scope.msg = "Error in filling departments drop down !"; }); } <-- Get the employee By ID. --> $scope.editEmployee = function (employee) { debugger; GetDesignations(); GetDepartments(); var getData = myService.getEmployee(employee.Id); getData.then(function (emp) { $scope.employee = emp.data; $scope.employeeId = employee.Id; $scope.employeeName = employee.name; $scope.employeeDOB = new Date(employee.DOB); $scope.employeeGender = employee.Gender; $scope.employeeEmail = employee.Email; $scope.employeeMobile = employee.Mobile; $scope.employeeAddress = employee.Address; $scope.employeeJoiningDate = employee.JoiningDate; $scope.employeeDepartment = employee.DepartmentID; $scope.employeeDesignation = employee.DesignationID; $scope.Action = "Edit"; $("#myModal").modal('show'); }, function (msg) { $("#alertModal").modal('show'); $scope.msg = msg.data; }); } <-- Insertion and updation code. --> $scope.AddUpdateEmployee = function () { var Employee = { Name: $scope.employeeName, DOB: $scope.employeeDOB, Gender: $scope.employeeGender, Email: $scope.employeeEmail, Mobile: $scope.employeeMobile, Address: $scope.employeeAddress, JoiningDate: $scope.employeeJoiningDate, DepartmentID: $scope.employeeDepartment, DesignationID: $scope.employeeDesignation }; var getAction = $scope.Action; if (getAction == "Edit") { Employee.Id = $scope.employeeId; var getData = myService.updateEmp(Employee); getData.then(function (msg) { GetAllEmployee(); ClearFields(); $("#alertModal").modal('show'); $scope.msg = msg.data; }, function (msg) { $("#alertModal").modal('show'); $scope.msg = msg.data; }); } else { var getData = myService.AddEmp(Employee); getData.then(function (msg) { GetAllEmployee(); $("#alertModal").modal('show'); $scope.msg = msg.data; ClearFields(); }, function (msg) { $("#alertModal").modal('show'); $scope.msg = msg.data; }); } debugger; GetAllEmployee(); $scope.refresh(); } <-- Clear fields after save --> function ClearFields() { $scope.employeeId = ""; $scope.employeeName = ""; $scope.employeeDOB = ""; $scope.employeeGender = ""; $scope.employeeEmail = ""; $scope.employeeMobile = ""; $scope.employeeAddress = ""; $scope.employeeJoiningDate = ""; $scope.employeeDepartment = ""; $scope.employeeDesignation = ""; }
- 开始在 Service.js 中编写代码。
- 在服务中,我们使用 $http 来调用服务器代码,并以我们想要的任何格式传递数据/参数。我们以 JSON 格式传递数据并以 JSON 格式获取数据。
- AddEmp 方法调用服务器上的 AddEmployee 方法,并传入来自视图的数据。
- getEmployee 方法调用服务器上的 getEmployeeByNo 方法来编辑记录。
- Update 方法调用服务器上的 UpdateEmployee 方法进行更新操作。
- 另外 2 个方法调用服务器来绑定下拉列表。
<-- Calls Add Employee method on server --> this.AddEmp = function (employee) { var response = $http({ method: "post", url: "/Employee/AddEmployee", data: JSON.stringify(employee), dataType: "json" }); return response; } <-- Calls get Employee By Id method on server --> this.getEmployee = function (employeeID) { var response = $http({ method: "post", url: "/Employee/getEmployeeByNo", params: { id: JSON.stringify(employeeID) } }); return response; } <--Calls the update method on server --> this.updateEmp = function (employee) { var response = $http({ method: "post", url: "/Employee/UpdateEmployee", data: JSON.stringify(employee), dataType: "json" }); return response; } <-- Calls the method on server for Designation dropdownlist --> this.GetDesignations = function () { return $http.get("/Employee/GetDesignations"); }; <-- Calls the method on server for Department dropdownlist --> this.GetDepartment = function () { return $http.get("/Employee/GetDepartments"); };
- 在此处查看 Employee.cshtml 代码。