码迷,mamicode.com
首页 > Windows程序 > 详细

[angularjs] MVC + Web API + AngularJs 搭建简单的 CURD 框架

时间:2017-05-01 13:41:17      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:empty   布局   技术   block   next   entity   sed   htm   key   

MVC + Web API + AngularJs 搭建简单的 CURD 框架

  GitHub 地址:https://github.com/liqingwen2015/Wen.MvcSinglePage

 

简介

  AngularJS[1]  诞生于2009年,由Misko Hevery 等人创建,后为Google所收购。是一款优秀的前端JS框架,已经被用于Google的多款产品当中。AngularJS有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入等等。

技术分享

 

技术分享

 

  布局页的引用

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    @*angularJs*@
    <script src="~/Scripts/angular-js/angular.js"></script>
    <script src="~/Scripts/angular-js/angular-route.js"></script>
    @*angularJs 自定义的配置*@
    <script src="~/Scripts/core/app.js"></script>
    <script src="~/Scripts/core/app-route.js"></script>
    <script src="~/Scripts/core/app-service.js"></script>
    @*angularJs 自定义的控制器*@
    <script src="~/Scripts/core/controllers/demoController.js"></script>

 

   app.js

var app = angular.module(‘myApp‘, [‘ngRoute‘, ‘demoService‘, ]);

  

  app-route.js

//路由配置
app.config([‘$routeProvider‘, function ($routeProvider) {
    $routeProvider
    .when(‘/‘, { templateUrl: ‘../Scripts/core/views/demo/index.html‘, controller: ‘demoController‘ })
    .when(‘/home‘, { templateUrl: ‘../Scripts/core/views/demo/index.html‘, controller: ‘demoController‘ })
    .when(‘/add‘, { templateUrl: ‘../Scripts/core/views/demo/edit.html‘, controller: ‘demoEditController‘ })
    .when(‘/edit/:id‘, { templateUrl: ‘../Scripts/core/views/demo/edit.html‘, controller: ‘demoEditController‘ })
    .when(‘/error‘, { templateUrl: ‘../Scripts/Views/Error.html‘, controller: ‘errorController‘ })
    .otherwise({ redirectTo: ‘/error‘ });
}]);

 

  app-service.js

//服务
var demoService = angular.module(‘demoService‘, []);

//请求服务
demoService.factory(‘requestService‘, function ($http, $q) {
    var params = {
        method: ‘‘,
        url: ‘‘,
        headers: { ‘Content-Type‘: ‘application/json‘ },
        data: {}
    }
    var request = {
        //
        add: function (data) {
            params.method = "post";
            params.url = "../api/demo/add";
            params.data = data;
            return requestService($http, $q, params);
        },
        //
        del: function (id) {
            params.method = "delete";
            params.url = "../api/demo/del?id=" + id;
            return requestService($http, $q, params);
        },
        //
        update: function (data) {
            params.method = "put";
            params.url = "../api/demo/update";
            params.data = data;
            return requestService($http, $q, params);
        },
        //
        get: function (id) {
            params.method = "get";
            params.url = "../api/demo/get?id=" + id;
            return requestService($http, $q, params);
        },
        //分页
        details: function (key, pageIndex) {
            params.method = "get";
            params.url = "../api/demo/details?key=" + key + "&pageIndex=" + pageIndex;
            return requestService($http, $q, params);
        }
    };

    return request;
});

//请求服务
function requestService($http, $q, request) {
    return $http(request);
};

 

   demoController.js

app.controller(‘demoController‘, function ($scope, $http, $location, $routeParams, requestService) {
    console.log(‘demoController‘);

    var currentPageIndex = 1;
    $scope.list = [];

    //删除
    $scope.del = function (id) {
        requestService.del(id)
            .then(function (result) {
                var data = result.data;
                console.log(data);
            });
    };

    $scope.demoKey = $scope.demoKey ? $scope.demoKey : "";
    $scope.details = function (key, pageIndex) {
        requestService.details(key, pageIndex)
            .then(function (result) {
                var data = result.data;
                $scope.list = data;
            });
        console.log($scope.list);
    };
    $scope.details("", currentPageIndex);

    //查询
    $scope.search = function () {
        $scope.list = [];
        $scope.details($scope.demoKey, currentPageIndex);
    };

    //新增
    $scope.add = function () {
        $location.url(‘/add‘);
    };

    //编辑
    $scope.edit = function (id) {
        $location.url(‘/edit/‘ + id);
    };

    //下一页
    $scope.nextPage = function () {
        currentPageIndex++;
        $scope.details($scope.demoKey, currentPageIndex);
    };

    //上一页
    $scope.prePage = function () {
        if (currentPageIndex > 1) {
            currentPageIndex--;
        }
        $scope.details($scope.demoKey, currentPageIndex);
    };
});

//demoEditController
app.controller(‘demoEditController‘,
    function ($scope, $http, $location, $routeParams, requestService) {
        console.log(‘demoEditController‘);

        $scope.demo = {
            Id: ‘‘,
            Name: ‘‘,
            Price: 0
        };

        var id = $routeParams.id;
        $scope.get = function () {
            requestService.get(id).then(function (result) {
                console.log(result);
                $scope.demo = result.data;
            });
        }
        if (id != null) { $scope.get(); }

        $scope.save = function () {
            if (id) {
                $scope.demo.Id = id;
                requestService.update($scope.demo).then(function (result) {
                    console.log(result);
                    var data = result.data;
                    console.log("更新成功");
                    console.log(data);
                });
            } else {
                requestService.add($scope.demo).then(function (result) {
                    console.log(result);
                    var data = result.data;
                    console.log("添加成功");
                    console.log(data);
                });
            };
        };

    });

 

  index.html

<div class="address_serace">
    <input class="form-control" ng-change="search()" ng-model="demoKey" placeholder="搜索">
</div>
<div class="address_div">
    <dl class="address_dl" ng-repeat="item in list">
        <dd class="address_font">
            <p class="address_font_t">{{item.Name}}</p>
            <p>单价:¥{{item.Price}}</p>
            <a ng-click="del(item.Id)">删除</a>
            <a ng-click="edit(item.Id)">编辑</a>
        </dd>
    </dl>

</div>

<button class="btn btn-primary btn-block " ng-click="prePage()">上一页...</button>
<button class="btn btn-primary btn-block " ng-click="nextPage()">下一页...</button>
<button class="btn btn-primary btn-block " ng-click="add()">添加</button>

 

  edit.html

<input type="text"
       name="name" class="form-control" placeholder="商品" ng-model="demo.Name" required />

<input type="text"
       name="name" class="form-control" placeholder="价格" ng-model="demo.Price" required />
<button class="btn btn-primary btn-block" ng-click="save()">保存</button>

 

  API:Demo 控制器

技术分享
#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Wen.MvcSinglePage.Models.Api;

#endregion

namespace Wen.MvcSinglePage.Controllers.Api
{
    public class DemoController : ApiController
    {
        private IList<DemoViewModel> _demos = new List<DemoViewModel>();

        public DemoController()
        {
            InitDemo();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="demo"></param>
        /// <returns></returns>
        [HttpPost]
        public DemoViewModel Add([FromBody] DemoViewModel demo)
        {
            _demos.Add(demo);

            return demo;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public DemoViewModel Get(int id)
        {
            return _demos.FirstOrDefault(x => x.Id == id);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public int Del(int id = 0)
        {
            var demo = _demos.FirstOrDefault(x => x.Id == id);
            if (demo != null)
                _demos.Remove(demo);

            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="demo"></param>
        /// <returns></returns>
        [HttpPut]
        public DemoViewModel Update([FromBody] DemoViewModel demo)
        {
            var entity = _demos.FirstOrDefault(x => x.Id == demo.Id);
            if (entity == null) return demo;

            entity.Name = demo.Name;
            entity.Price = demo.Price;

            return demo;
        }

        /// <summary>
        /// 详情(分页)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<DemoViewModel> Details(string key, int pageIndex)
        {
            const int pageSize = 5;
            if (!string.IsNullOrEmpty(key))
            {
                _demos = _demos.Where(x => x.Name.Contains(key)).ToList();
            }

            return _demos.Skip(pageSize * (pageIndex - 1)).Take(pageSize);
        }

        /// <summary>
        /// 初始化 Demo
        /// </summary>
        private void InitDemo()
        {
            var random = new Random();
            for (var i = 0; i < 100; i++)
            {
                _demos.Add(new DemoViewModel
                {
                    Id = i,
                    Name = $"商品:{i}",
                    Price = random.Next()
                });
            }

        }
    }
}
DemoController.cs

技术分享

 

 GitHub 地址:https://github.com/liqingwen2015/Wen.MvcSinglePage

 

 


【博主】反骨仔

【出处】http://www.cnblogs.com/liqingwen/p/6713612.html

【参考】http://www.cnblogs.com/wolf-sun/p/5279175.html

[angularjs] MVC + Web API + AngularJs 搭建简单的 CURD 框架

标签:empty   布局   技术   block   next   entity   sed   htm   key   

原文地址:http://www.cnblogs.com/liqingwen/p/6713612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!