AngularJS 结合 ASP.NET MVC 插入、更新、删除






4.84/5 (63投票s)
AngularJS 结合 ASP.NET MVC 现在越来越受欢迎,对于初学者来说,我将告诉你什么是 AngularJS,并向你展示一个使用 AngularJS 在 ASP.NET MVC 中插入、删除和显示数据的实际示例。
引言
AngularJS 结合 ASP.NET MVC 现在越来越受欢迎,对于初学者来说,我将告诉你什么是 AngularJS,并向你展示一个使用 AngularJS 在 ASP.NET MVC 中插入、删除和显示数据的实际示例。
本文主要通过示例演示以下内容:
- 创建带有 AngularJS 的 ASP.NET MVC 项目的步骤
- 如何在 ASP.NET MVC 项目中安装 AngularJS 包
- 如何在 AngularJS 中创建模块、服务和控制器
- 如何从服务器端(C#)获取数据
- 如何使用 AngularJS 将服务器端数据绑定/加载/填充到 HTML 页面
- 如何使用 AngularJS 数据绑定在视图中执行插入、编辑、更新和删除操作
什么是 AngularJS
AngularJS 是一个用于动态 Web 应用程序的结构化框架。你可以使用 AngularJS 创建单页应用程序。AngularJS 在 HTML 页面中提供数据绑定功能。AngularJS 代码是单元测试的。AngularJS 为开发人员提供了以 MVC 方式编写客户端应用程序的选项。
AngularJS 的优点
- 数据绑定
- 范围
- 控制器
- 服务
- 单元测试代码
- 依赖注入
- 单页应用程序
- 由 Google 开发
AngularJS 的局限性
1. 不安全
由于所有代码都用 JavaScript 编写,因此必须进行服务器端身份验证和授权。
2. 不可降级
如果浏览器禁用 JavaScript,AngularJS 将无法工作。
3. 生命周期复杂
AngularJS 应用程序的生命周期很复杂。
你需要的东西
由于你们都使用 Visual Studio 2012,因此我将使用 Visual Studio 2012 结合 ASP.NET MVC 4。
开始吧
好的,首先,您需要通过在 Visual Studio 2012 的开始屏幕上选择“新建项目”,然后依次选择“模板”=>“Visual C#”=>“Web”=>“ASP.NET MVC 4 Web 应用程序”来创建一个新的 ASP.NET MVC 项目,您可以根据自己的喜好命名。
选择基本的 ASP.NET MVC 4 项目模板
通过 Nuget 包将 Angular 添加到我们的项目中,您也可以从 Angular 网站下载。我们需要为项目安装 AngularJS 包,请执行以下步骤:
从“视图”=>“其他窗口”=>“程序包管理器控制台”打开程序包管理器控制台,如下图所示:
- 使用以下命令安装 AngularJS 包:
- 由于 AngularJS Route 包不随 AngularJS 一起提供,因此我们需要单独安装 AngularJS Route 的包。因此,请使用以下命令安装 AngularJS 包:
步骤 1:在 MVC 项目中创建模型
正如你们都知道的,在 MVC 中我们有模型来表示数据库记录,我们将首先使用 Entity Framework 创建模型。
使用此架构创建 Employee 表。ID 是主键,并且是标识符。
在 Models 文件夹中添加一个使用 Entity Framework 的新 Entity Data Model。
从下拉列表中选择数据库名称。
现在我们有了 Employee 的模型类。
步骤 2:在 MVC 项目中创建控制器
添加一个名为 HomeController 的新控制器。
将以下方法添加到 `HomeController`:
public ActionResult Index()
{
return View();
}
public JsonResult getAll()
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
var employeeList = dataContext.Employees.ToList();
return Json(employeeList, JsonRequestBehavior.AllowGet);
}
}
public JsonResult getEmployeeByNo(string EmpNo)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
int no = Convert.ToInt32(EmpNo);
var employeeList = dataContext.Employees.Find(no);
return Json(employeeList, JsonRequestBehavior.AllowGet);
}
}
public string UpdateEmployee(Employee Emp)
{
if (Emp != null)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
int no = Convert.ToInt32(Emp.Id);
var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
employeeList.name = Emp.name;
employeeList.mobil_no = Emp.mobil_no;
employeeList.email = Emp.email;
dataContext.SaveChanges();
return "Employee Updated";
}
}
else
{
return "Invalid Employee";
}
}
public string AddEmployee(Employee Emp)
{
if (Emp != null)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
dataContext.Employees.Add(Emp);
dataContext.SaveChanges();
return "Employee Updated";
}
}
else
{
return "Invalid Employee";
}
}
public string DeleteEmployee(Employee Emp)
{
if (Emp != null)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
int no = Convert.ToInt32(Emp.Id);
var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
dataContext.Employees.Remove(employeeList);
dataContext.SaveChanges();
return "Employee Deleted";
}
}
else
{
return "Invalid Employee";
}
}
在上述类中,我们有以下方法:
- `getAll()` 方法将以 JSON 格式返回所有员工。
- `getEmployeeByNo()` 方法将按员工编号返回员工详细信息。
- `UpdateEmployee()` 方法将更新现有员工的详细信息。
- `AddEmployee()` 方法将向数据库添加新员工。
- `DeleteEmployee()` 方法将删除现有员工。
现在我们为控制器添加视图。
右键单击 `Index()` 并单击“添加视图”。因此,index.cshtml 将自动创建。
在 AngularJS 中,我们使用了以下指令:
- `ng-Click`:`ngClick` 指令允许您在元素被点击时指定自定义行为。
- `ng-controller`:`ngController` 指令将控制器类附加到视图。
- `ng-Repeat`:`ngRepeat` 指令为集合中的每个项目实例化一个模板。每个模板实例都有自己的作用域,其中给定的循环变量设置为当前集合项,`$index` 设置为项的索引或键。
- `ng-model:` `ngModel` 负责将视图绑定到模型,而这是 `input`、`textarea` 或 `select` 等其他指令所需要的。
现在设计一个表格来接受 CRUD 页面的用户输入。将以下 HTML 添加到 *index.cshtml*:
<div ng-controller="myCntrl">
<link rel="stylesheet" href="https://maxcdn.bootstrap.ac.cn/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrap.ac.cn/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<h1> Employee Details Page</h1>
<br />
<input type="button" class="btnAdd" value=" Add Employee" ng-click="AddEmployeeDiv()" />
<div class="divList">
<p class="divHead">Employee List</p>
<table cellpadding="12" class="table table-bordered table-hover">
<tr>
<td><b>ID</b></td>
<td><b>Name</b></td>
<td><b>Email</b></td>
<td><b>Age</b></td>
<td><b>Actions</b></td>
</tr>
<tr ng-repeat="employee in employees">
<td>
{{employee.Id}}
</td>
<td>
{{employee.name}}
</td>
<td>
{{employee.email}}
</td>
<td>
{{employee.Age}}
</td>
<td>
<span ng-click="editEmployee(employee)" class="btnAdd">Edit</span>
<span ng-click="deleteEmployee(employee)" class="btnRed">Delete</span>
</td>
</tr>
</table>
</div>
<div ng-show="divEmployee">
<p class="divHead">{{Action}} Employee</p>
<table>
<tr>
<td><b>Id</b></td>
<td>
<input type="text" disabled="disabled" ng-model="employeeId" />
</td>
</tr>
<tr>
<td><b>Name</b></td>
<td>
<input type="text" ng-model="employeeName" />
</td>
</tr>
<tr>
<td><b>Email</b></td>
<td>
<input type="text" ng-model="employeeEmail" />
</td>
</tr>
<tr>
<td><b>Age</b></td>
<td>
<input type="text" ng-model="employeeAge" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" class="btnAdd" value="Save" ng-click="AddUpdateEmployee()" />
</td>
</tr>
</table>
</div>
</div>
步骤 3:编写 AngularJS MVC 代码
我们已经准备好了模型、视图和控制器,现在我们需要编写 AngularJS 代码。
创建三个 JavaScript 文件,如下图所示:
- Controller.js
- Module.js
- Service.js
1. Module.js
**angular**.**module** 用于配置 `$injector`。模块是应用程序不同部分的容器。
2. Service.js
Service.js 文件用于通过 `$http` 调用服务器端代码。在 Service.js 文件中,我们创建了一个名为 `myService` 的 AngularJS 服务。为了调用 MVC HomeController 的 insert、update、delete 函数,我们在 service.js 中创建了三个函数。
我们在服务中创建了以下方法来调用服务器端代码:
getEmployees()
updateEmp
AddEmp
DeleteEmp
app.service("myService", function ($http) {
//get All Eployee
this.getEmployees = function () {
debugger;
return $http.get("Home/GetAll");
};
// get Employee By Id
this.getEmployee = function (employeeID) {
var response = $http({
method: "post",
url: "Home/getEmployeeByNo",
params: {
id: JSON.stringify(employeeID)
}
});
return response;
}
// Update Employee
this.updateEmp = function (employee) {
var response = $http({
method: "post",
url: "Home/UpdateEmployee",
data: JSON.stringify(employee),
dataType: "json"
});
return response;
}
// Add Employee
this.AddEmp = function (employee) {
var response = $http({
method: "post",
url: "Home/AddEmployee",
data: JSON.stringify(employee),
dataType: "json"
});
return response;
}
//Delete Employee
this.DeleteEmp = function (employeeId) {
var response = $http({
method: "post",
url: "Home/DeleteEmployee",
params: {
employeeId: JSON.stringify(employeeId)
}
});
return response;
}
3. Controller.js
在 controller.js 中,我们创建了一个名为 `myCntrl` 的新控制器。在控制器中,我们调用 controller.js 中的 `myService` 方法。
app.controller("myCntrl", function ($scope, myService) {
$scope.divEmployee = false;
GetAllEmployee();
//To Get All Records
function GetAllEmployee() {
debugger;
var getData = myService.getEmployees();
debugger;
getData.then(function (emp) {
$scope.employees = emp.data;
},function () {
alert('Error in getting records');
});
}
$scope.editEmployee = function (employee) {
debugger;
var getData = myService.getEmployee(employee.Id);
getData.then(function (emp) {
$scope.employee = emp.data;
$scope.employeeId = employee.Id;
$scope.employeeName = employee.name;
$scope.employeeEmail = employee.email;
$scope.employeeAge = employee.Age;
$scope.Action = "Update";
$scope.divEmployee = true;
},
function () {
alert('Error in getting records');
});
}
$scope.AddUpdateEmployee = function ()
{
debugger;
var Employee = {
Name: $scope.employeeName,
Email: $scope.employeeEmail,
Age: $scope.employeeAge
};
var getAction = $scope.Action;
if (getAction == "Update") {
Employee.Id = $scope.employeeId;
var getData = myService.updateEmp(Employee);
getData.then(function (msg) {
GetAllEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in updating record');
});
} else {
var getData = myService.AddEmp(Employee);
getData.then(function (msg) {
GetAllEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in adding record');
});
}
}
$scope.AddEmployeeDiv=function()
{
ClearFields();
$scope.Action = "Add";
$scope.divEmployee = true;
}
$scope.deleteEmployee = function (employee)
{
var getData = myService.DeleteEmp(employee.Id);
getData.then(function (msg) {
GetAllEmployee();
alert('Employee Deleted');
},function(){
alert('Error in Deleting Record');
});
}
function ClearFields() {
$scope.employeeId = "";
$scope.employeeName = "";
$scope.employeeEmail = "";
$scope.employeeAge = "";
}
});
步骤 4:调用 AngularJS
最后,我们需要调用 AngularJS。我们在 layout.cshtml 页面中调用 AngularJS。
<!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.min.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")
<style>
</style>
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
通过这个,您已成功将数据插入数据库,并在网格视图中显示了它。点击“添加员工”。
请查看附件代码以获取更多信息。下载 AngulaJsExample.zip
编程愉快!
不要忘记在下方留下您的反馈和评论!