博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作
阅读量:6427 次
发布时间:2019-06-23

本文共 8858 字,大约阅读时间需要 29 分钟。

写在前面

前篇文章整理了angularjs学习目录,有园子里的朋友问我要这方面的demo,周末也没什么事,就在之前的单页应用的demo上面添加了增删改查的操作。代码比较简单,这里只列举比较重要的代码片段。完整的代码将在文章下面提供链接。

demo

数据来源通过webapi的方式提供。获取对产品的查询,分页,增加商品,删除,修改等操作。

webapi

public class ProductController : ApiController    {        private List
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
(); //分页用 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
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
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
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
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; }); } }
ProductController

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.js

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' });}]);
app-route.js

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);                }            });        };    };});
View Code

angularjs 视图

add-order.html

{

{item.Name}}

单价:¥{

{item.Price}}

删除
编辑
orders.html

静态资源引入存放在_Layout.cshtml文件中

    
@ViewBag.Title - My ASP.NET Single Page Application @* bootstrap *@
@* 站点样式 *@
@* angularjs *@ @* app *@ @* 路由 *@ @* 控制器 *@ @RenderBody()

列表页面

做的比较简单,能用就行。

添加商品和编辑商品使用同一个视图文件和controller,通过参数id来区别是编辑还是添加商品

测试

删除商品,根据id删除商品,前端根据_code判断是否删除成功,删除商品0,结果如下所示

加载更过,默认pageSize=10,加载第二页,如下图所示:

修改

总结

这里没有采用数据库,数据通过list模拟的,操作数据库的那部分,有兴趣的添加。

转载于:https://www.cnblogs.com/wolf-sun/p/5514185.html

你可能感兴趣的文章
示例化讲解RIP路由更新机制
查看>>
eclipse不能自动编译工程的解决方法
查看>>
Powershell管理系列(九)删除Exchange用户邮箱中多余的电子邮件地址
查看>>
Swt/Jface进度条
查看>>
.NET建议使用的大小写命名原则
查看>>
Git:错误:error:src refspec master does not match any
查看>>
SSIS 数据类型和类型转换
查看>>
Oracle数据库“Specified cast is农田valid”
查看>>
数据层新思路,写数据库无关的数据层 ORM在数据库内做更为合适
查看>>
armv8(aarch64)linux内核中flush_dcache_all函数详细分析【转】
查看>>
房地产英语 Real estate词汇
查看>>
python接口自动化测试(八)-unittest-生成测试报告
查看>>
第 26 章 MySQL
查看>>
C#中三种截屏方式总结
查看>>
Spring.net 学习笔记之ASP.NET底层架构
查看>>
C# System.Windows.Forms.WebBrowser中判断浏览器内核和版本
查看>>
Java 动态太极图 DynamicTaiChi (整理)
查看>>
微信公众平台后台编辑器上线图片缩放和封面图裁剪功能
查看>>
git使用教程2-更新github上代码
查看>>
张掖百公里,再次折戟
查看>>