[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作
Posted tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作相关的知识,希望对你有一定的参考价值。
写在前面
前篇文章整理了angularjs学习目录,有园子里的朋友问我要这方面的demo,周末也没什么事,就在之前的单页应用的demo上面添加了增删改查的操作。代码比较简单,这里只列举比较重要的代码片段。完整的代码将在文章下面提供链接。
demo
数据来源通过webapi的方式提供。获取对产品的查询,分页,增加商品,删除,修改等操作。
webapi
public class ProductController : ApiController { private List<Product> lstOrders = null; HttpResponseMessage response = null; public ProductController() { response = new HttpResponseMessage(HttpStatusCode.ResetContent); response.Headers.Add("Access-Control-Allow-Origin", "*"); //允许哪些url可以跨域请求到本域 response.Headers.Add("Access-Control-Allow-Methods", "POST"); //允许的请求方法,一般是GET,POST,PUT,DELETE,OPTIONS response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,content-type"); //允许哪些请求头可以跨域 lstOrders = new List<Product>(); //分页用 for (int i = 0; i < 100; i++) { lstOrders.Add(new Product { Dt = DateTime.Now, Id = i + 1, Name = "商品" + i.ToString(), Price = i + 20 }); } } // GET: api/Order [HttpGet] [Route("api/product/lists")] public async Task<HttpResponseMessage> Get(string key, int page) { return await Task.Factory.StartNew(() => { int pageSize = 10; var results = string.IsNullOrEmpty(key) ? lstOrders : lstOrders.Where(x => x.Name.Contains(key)); //分页 var pagedResults = results.Skip((page - 1) * pageSize).Take(pageSize); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _data = pagedResults })); return response; }); } [HttpPost] [Route("api/product/lists")] public async Task<HttpResponseMessage> Post([FromBody] Product order) { return await Task.Factory.StartNew(() => { //模拟id order.Id = new Random().Next(101, 5000); lstOrders.Add(order); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _data = order })); return response; }); } [HttpPut] [Route("api/product/lists")] // POST: api/Order public async Task<HttpResponseMessage> Put([FromBody] Product order) { return await Task.Factory.StartNew(() => { var find = lstOrders.Find(o => o.Id == order.Id); if (find != null) { find.Name = order.Name; find.Price = order.Price; find.Dt = order.Dt; response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _data = find })); } return response; }); } [HttpDelete] [Route("api/product/lists")] // DELETE: api/Order/5 public async Task<HttpResponseMessage> Delete(int id) { return await Task.Factory.StartNew(() => { Product findOder = lstOrders.Find(o => o.Id == id); lstOrders.Remove(findOder); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _data = lstOrders })); return response; }); } }
angularjs app.js文件,注册module,服务的注册。
var app = angular.module(\'app_store\', [\'ngRoute\', \'StoreService\', ]); //服务 var StoreService = angular.module(\'StoreService\', []); //请求服务 StoreService.factory(\'requestService\', function ($http, $q) { var request = { method: \'POST\', url: \'\', headers: { \'Content-Type\': \'application/json\' }, data: {} }; var postData = { lists: function (type, page) { request.method = "get"; request.url = "../api/product/lists?key=" + type + "&page=" + page; return requestService($http, $q, request); }, product_add: function (data) { request.method = "post"; request.url = "../api/product/lists"; request.data = data; return requestService($http, $q, request); }, product_delete: function (id) { request.method = "DELETE"; request.url = "../api/product/lists?id=" + id; return requestService($http, $q, request); }, product_put: function (data) { request.method = "put"; request.url = "../api/product/lists"; request.data = data; return requestService($http, $q, request); } }; return postData; }); function requestService($http, $q, request) { var deferred = $q.defer(); // 声明延后执行,表示要去监控后面的执行 $http(request). success(function (data, status, headers, config) { deferred.resolve(data); // 声明执行成功,即http请求数据成功,可以返回数据了 }). error(function (data, status, headers, config) { deferred.reject(data); // 声明执行失败,即服务器返回错误 }); return deferred.promise; // 返回承诺,这里并不是最终数据,而是访问最终数据的API };
app-route.js angularjs路由配置。
app.config([\'$routeProvider\', function ($routeProvider) { $routeProvider .when(\'/\', { templateUrl: \'../Scripts/Views/orders.html\', controller: \'StoreController\' }) .when(\'/home\', { templateUrl: \'../Scripts/Views/orders.html\' }) .when(\'/add\', { templateUrl: \'../Scripts/Views/add-order.html\', controller: \'OrderController\' }) .when(\'/edit/:id\', { templateUrl: \'../Scripts/Views/add-order.html\', controller: \'OrderController\' }) .when(\'/error\', { templateUrl: \'../Scripts/Views/Error.html\', controller: \'ErrorController\' }) .otherwise({ redirectTo: \'/error\' }); }]);
StoreController.js angularjs控制器
app.controller(\'StoreController\', function ($scope, $http, $location, $routeParams, requestService) { console.log(\'StoreController\'); var page = 1; $scope.productKey = $scope.productKey ? $scope.productKey : \'\'; $scope.products = []; $scope.query = function (key, page) { requestService.lists(key, page).then(function (data) { if (data._code === 200) { for (var i = 0; i < data._data.length; i++) { $scope.products.push(data._data[i]); }; }; }); console.log($scope.products); }; $scope.query(\'\', page) //查询 $scope.search = function () { $scope.products = []; $scope.query($scope.productKey, page) }; $scope.add = function () { $location.url(\'/add\'); }; $scope.loadMore = function () { page++; $scope.query($scope.productKey, page) }; $scope.delte = function (id) { requestService.product_delete(id).then(function (data) { console.log(data); if (data._code == 200) { console.log(\'删除成功\'); console.log(data._data); } }); }; $scope.edit = function (id) { $location.url(\'/edit/\' + id); }; }); app.controller(\'OrderController\', function ($scope, $http, $location, $routeParams, requestService) { console.log(\'OrderController\'); $scope.product = { Id: \'\', Name: \'\', Price: 0 }; var id = $routeParams.id; $scope.btn = id ? \'确定\' : \'添加\'; $scope.add = function () { if (id) { $scope.product.Id = id; requestService.product_put($scope.product).then(function (data) { console.log(data); if (data._code == 200) { console.log(\'修改成功\'); console.log(data._data); } }); } else { requestService.product_add($scope.product).then(function (data) { console.log(data); if (data._code == 200) { console.log(\'添加成功\'); console.log(data._data); } }); }; }; });
angularjs 视图
<input type="text" name="name" class="form-control" placeholder="订单名" ng-model="product.Name" required /> <input type="text" name="name" class="form-control" placeholder="单价" ng-model="product.Price" required /> <button class="btn btn-primary btn-block" ng-click="add()">{{btn}}</button>
<div class="address_serace"> <input class="form-control" ng-change="search()" ng-model="productKey" placeholder="搜索商品"> </div> <div class="address_div"> <dl class="address_dl" ng-repeat="item in products"> <dt class="address_user"><img class="address_user" src="/Content/Images/main.png" /></dt> <dd class="address_font"> <p class="address_font_t">{{item.Name}}</p> <p>单价:¥{{item.Price}}</p> <a ng-click="delte(item.Id)">删除</a> <a ng-click="edit(item.Id)">编辑</a> </dd> </dl> </div> <button class="btn btn-primary btn-block " ng-click="loadMore()">加载更多...</button> <button class="btn btn-primary btn-block " ng-click="add()" >添加</button>
静态资源引入存放在_Layout.cshtml文件中
<!DOCTYPE html> <html ng-app="app_store"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Single Page Application</title> @* bootstrap *@ <link href=@Url.Content("~/Content/bootstrap.min.css") rel="stylesheet" /> @* 站点样式 *@ <link href=@Url.Content("~/Content/Site.css") rel="stylesheet" /> @* angularjs *@ <script src=@Url.Content("~/Scripts/App/angular.min.js")></script> <script src=@Url.Content("~/Scripts/App/angular-route.min.js")></script> @* app *@ <script src=@Url.Content("~/Scripts/App/Apps.js")></script> @* 路由 *@ <script src=@Url.Content("~/Scripts/Route/app-route.js")></script> @* 控制器 *@ <script src=@Url.Content("~/Scripts/Controllers/StoreController.js")></script> </head> <body> @RenderBody() </body> </html>
列表页面
做的比较简单,能用就行。
添加商品和编辑商品使用同一个视图文件和controller,通过参数id来区别是编辑还是添加商品
测试
删除商品,根据id删除商品,前端根据_code判断是否删除成功,删除商品0,结果如下所示
加载更过,默认pageSize=10,加载第二页,如下图所示:
修改
总结
这里没有采用数据库,数据通过list模拟的,操作数据库的那部分,有兴趣的添加。
以上是关于[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作的主要内容,如果未能解决你的问题,请参考以下文章