开发者社区> ghost丶桃子> 正文

[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作

简介:
+关注继续查看

写在前面

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

demo

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

webapi

复制代码
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Wolfy.Angularjs_Mvc_SPA.Models;

namespace Wolfy.Angularjs_Mvc_SPA.Controllers.api
{
    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 = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    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 = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    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 = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        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 = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    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模拟的,操作数据库的那部分,有兴趣的添加。

 demo源码

博客地址: http://www.cnblogs.com/wolf-sun/
博客版权: 本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。
如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步!
再次感谢您耐心的读完本篇文章。http://www.cnblogs.com/wolf-sun/p/5514185.html

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
VC++ 操作MySql数据库
 #include MYSQL mysql;MYSQL_RES* query;//结果集MYSQL_ROW row;//记录集 //初始化if (!mysql_init(&mysql)){  //errc = 1;} //连接MYSQL                     "127.
748 0
BLE Scanner应用开发实例
本文介绍了如何使用YoC蓝牙协议栈和CH6121开发板进行BLE Scanner应用开发的过程。
749 0
Asp.Net Web API 2第二课——CRUD操作
原文:Asp.Net Web API 2第二课——CRUD操作 Asp.Net Web API 导航     Asp.Net Web API第一课——入门http://www.cnblogs.com/aehyok/p/3432158.html 前言   CRUD代表着 Create、Read、Update、Delete,这是四个基本的数据库操作。
1330 0
使用Java Api 对HBase进行简单操作
/** * 功能:测试Hbase基本的增删改查操作 * Created by liuhuichao on 2016/12/5. */ public class HbaseCRUDTest { public static Configuration configuration...
910 0
1955
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
JS零基础入门教程(上册)
立即下载
性能优化方法论
立即下载
手把手学习日志服务SLS,云启实验室实战指南
立即下载