第六章 用户管理

源代码GitHub:https://github.com/ZhaoRd/Zrd_0001_AuthorityManagement

1.介绍

    用户管理主要是针对系统所有用户的管理功能,试图提供一个用户列表,以便管理员维护用户列表。

    本章主要介绍内容:angle的表格、angularjs表单验证、分页,后端代码查询等功能。

    界面预览是整个Demo所采用的列表和操作方式。

2.界面预览

e7f96a6b-2697-4a56-aed2-f8211bf75da6

图2-1

5e20979d-b228-4807-aeaa-d5103f678cfd

图2-2

f8ab6ea2-9a2c-4406-a7ed-87abd6bfd5b3

图2-3

点击图2-1中的新增用户按钮,则弹出图2-2。

在图2-2中,如果不输入用户名,这提示必须输入用户名,输入用户名后,点击保存,保存结果会显示在图2-1中的“操作通知区域”。

点击图2-1列表内的删除按钮,则弹出图2-3,操作结果显示在图2-1中的"操作通知区域"。

3.功能实现

3.1 前台代码

 

   1 @{
   2 
   3 this.Layout = null;
   4 
   5 ViewBag.Title = "List";
   6 
   7 }
   8 
   9  
  10 
  11 <h3>用户管理</h3>
  12 
  13  
  14 
  15 <div class="panel panel-default" ng-controller="SearchController as panel">
  16 
  17 
  18 
  19 <div ng-class="{'panel-heading-collapsed':panelSearch}" class="panel-heading">
  20 
  21 <em class="fa fa-filter"></em>搜索条件|
  22 
  23 <small>设置搜索用户条件</small>
  24 
  25  
  26 
  27 <div class="pull-right" tool-collapse="tool-collapse">
  28 
  29 <a class="ng-scope" ng-click="panelSearch = !panelSearch"
  30 
  31 panel-collapse="" >
  32 
  33 <em class="fa fa-plus ng-hide" ng-show="panelSearch" style=""></em>
  34 
  35 <em class="fa fa-minus" ng-show="!panelSearch" style=""></em>
  36 
  37 </a>
  38 
  39 
  40 
  41 </div>
  42 
  43 
  44 
  45 </div>
  46 
  47 
  48 
  49 <div collapse="panelSearch" class="panel-wrapper">
  50 
  51 <div class="panel-body">
  52 
  53 <form name="formSearch" ng-submit="panel.submitForm()"
  54 
  55 novalidate="" class="form-horizontal">
  56 
  57 
  58 
  59 <div class="form-group">
  60 
  61 <label class="col-lg-3 control-label">用户名</label>
  62 
  63 <div class="col-lg-6">
  64 
  65 <input type="text" name="username" required="" ng-model="filter.username" class="form-control" />
  66 
  67 
  68 
  69 </div>
  70 
  71 </div>
  72 
  73 <div class="form-group">
  74 
  75 <label class="col-lg-3 control-label"></label>
  76 
  77 <div class="col-lg-6">
  78 
  79 <button type="submit" class="btn btn-info">搜索</button>
  80 
  81 <button type="reset" class="btn btn-danger">重置</button>
  82 
  83 </div>
  84 
  85 
  86 
  87 </div>
  88 
  89 </form>
  90 
  91 </div>
  92 
  93 </div>
  94 
  95  
  96 
  97 </div>
  98 
  99  
 100 
 101 <div class="panel panel-default">
 102 
 103 
 104 
 105 <div class="panel-heading" ng-controller="OperationController as operation">
 106 
 107 <em class="fa fa-table"></em>用户列表
 108 
 109 
 110 
 111 <div class="pull-right">
 112 
 113 <button class="btn btn-labeled btn-info" type="button"
 114 
 115 ng-click="operation.add()">
 116 
 117 <span class="btn-label">
 118 
 119 <i class="fa fa-plus"></i>
 120 
 121 </span>
 122 
 123 新增用户
 124 
 125 </button>
 126 
 127 </div>
 128 
 129  
 130 
 131 </div>
 132 
 133 <div class="panel-body">
 134 
 135 
 136 
 137 <div class="row" ng-controller="DataTableController as table1">
 138 
 139 <div class="col-lg-12">
 140 
 141 <table datatable="ng" class="row-border hover"
 142 
 143 dt-options="table1.dtOptions"
 144 
 145 dt-column-defs="table1.dtColumnDefs">
 146 
 147 <thead>
 148 
 149 <tr>
 150 
 151 <th>ID</th>
 152 
 153 <th>姓名</th>
 154 
 155 <th>邮箱</th>
 156 
 157 <th>操作</th>
 158 
 159 </tr>
 160 
 161 </thead>
 162 
 163 <tbody>
 164 
 165 <tr ng-repeat="person in table1.persons.list">
 166 
 167 <td>{{ person.Id }}</td>
 168 
 169 <td>{{ person.UserName }}</td>
 170 
 171 <td>{{ person.Email }}</td>
 172 
 173 <td>
 174 
 175 <button type="button" ng-click="table1.edit(person.Id)" class="btn btn-sm btn-warning"
 176 
 177 ng-disabled="person.UserName=='super'">
 178 
 179 <em class="fa fa-edit"></em>编辑
 180 
 181 </button>
 182 
 183 <button type="button" ng-click="table1.delete(person.Id)" class="btn btn-sm btn-danger"
 184 
 185 ng-disabled="person.UserName=='super'">
 186 
 187 <em class="fa fa-trash-o"></em>删除
 188 
 189 </button>
 190 
 191 </td>
 192 
 193 </tr>
 194 
 195 </tbody>
 196 
 197 </table>
 198 
 199 </div>
 200 
 201 </div>
 202 
 203 <div class="row" ng-controller="UserPagingController as pag">
 204 
 205 <div class="col-lg-3" style="margin-top: 21px">
 206 
 207 <span>每页显示</span>
 208 
 209 <div dropdown="dropdown" class="btn-group">
 210 
 211 <button dropdown-toggle="" class="btn btn-default">{{pag.paging.pageSize}} <b class="caret"></b>
 212 
 213 </button>
 214 
 215 <ul role="menu" class="dropdown-menu animated fadeIn">
 216 
 217 
 218 
 219 <li ng-repeat="sizeitem in pag.pageSizes">
 220 
 221 <a ng-click="pag.pageSizeChanged(sizeitem)">{{sizeitem}}</a>
 222 
 223 </li>
 224 
 225 </ul>
 226 
 227 </div>
 228 
 229 条数据
 230 
 231 </div>
 232 
 233 <div class="col-lg-9">
 234 
 235 <pagination total-items="pag.paging.total"
 236 
 237 ng-model="pag.paging.currentPage"
 238 
 239 max-size="pag.paging.pageSize"
 240 
 241 items-per-page="pag.paging.pageSize"
 242 
 243 boundary-links="true" rotate="false"
 244 
 245 num-pages="pag.numPages"
 246 
 247 ng-change="pag.pageChanged()"
 248 
 249 previous-text="上一页"
 250 
 251 next-text="下一页"
 252 
 253 first-text="首页"
 254 
 255 last-text="尾页"
 256 
 257 class="pagination-sm"></pagination>
 258 
 259 <pre> 显示第 {{(pag.paging.currentPage-1)*pag.paging.pageSize+1}} 至 {{pag.paging.currentPage*pag.paging.pageSize < pag.paging.total ? pag.paging.currentPage*pag.paging.pageSize:pag.paging.total}} 项结果,共 {{pag.paging.total}} 项;当前第 {{pag.paging.currentPage}} 页,共 {{pag.numPages}} 页 </pre>
 260 
 261 </div>
 262 
 263 </div>
 264 
 265 </div>
 266 
 267 </div>
 268 
 269  
 270 
 271 <toaster-container toaster-options="{'position-class': 'toast-bottom-right', 'close-button':true}"></toaster-container>
 272 
 273  
 274 
 275  
 276 
 277 <script type="text/ng-template" id="myModalContent.html">
 278 
 279 <div class="modal-header">
 280 
 281 <h3 class="modal-title">编辑用户</h3>
 282 
 283 </div>
 284 
 285 <div class="modal-body">
 286 
 287 <form name="formValidate" ng-submit="submitForm()"
 288 
 289 novalidate="" class="form-validate form-horizontal">
 290 
 291 
 292 
 293 <div class="form-group">
 294 
 295 <label class="col-lg-3 control-label">用户名<small class="text-muted">*</small></label>
 296 
 297 <div class="col-lg-6">
 298 
 299 <input type="text" name="username" required="" ng-model="user.UserName" class="form-control" />
 300 
 301 
 302 
 303 </div>
 304 
 305 <div class="col-lg-3 ">
 306 
 307 <span ng-show="validateInput('username', 'required')" class="text-danger">
 308 
 309 必须填入用户名
 310 
 311 </span>
 312 
 313 </div>
 314 
 315 </div>
 316 
 317 
 318 
 319 </form>
 320 
 321 
 322 
 323 </div>
 324 
 325 <div class="modal-footer">
 326 
 327 <button class="btn btn-primary" type="button" ng-click="submitForm()">保存</button>
 328 
 329 <button class="btn btn-warning" type="button" ng-click="cancel()">取消</button>
 330 
 331 </div>
 332 
 333 </script>
 334 
 335  
 336 
 337  
 338 
 339 <script type="text/javascript">
 340 
 341 
 342 
 343 // #region 检索面板的处理
 344 
 345 
 346 
 347 (function() {
 348 
 349 'use strict';
 350 
 351  
 352 
 353 var app = angular.module('angle');
 354 
 355  
 356 
 357 app.register.controller('SearchController', ['$scope', 'UserManagerService', function ($scope, UserManagerService) {
 358 
 359 var vm = this;
 360 
 361 activate();
 362 
 363  
 364 
 365 ////////////////
 366 
 367  
 368 
 369 function activate() {
 370 
 371  
 372 
 373 vm.filter = UserManagerService.filter;
 374 
 375  
 376 
 377 vm.submitForm =function() {
 378 
 379 UserManagerService.getUserList();
 380 
 381 };
 382 
 383  
 384 
 385 }
 386 
 387  
 388 
 389 }]);
 390 
 391  
 392 
 393 })();
 394 
 395  
 396 
 397 // #endregion
 398 
 399  
 400 
 401 // #region 用户管理业务
 402 
 403 (function () {
 404 
 405 'use strict';
 406 
 407  
 408 
 409 angular.module('angle').register.factory('UserManagerService', ['$http', '$q', function ($http, $q) {
 410 
 411 var self = this;
 412 
 413 self.userInfo = {
 414 
 415 list: []
 416 
 417 };
 418 
 419 self.filter = {
 420 
 421 username: ''
 422 
 423 };
 424 
 425  
 426 
 427 self.paging = {
 428 
 429 currentPage: 1,
 430 
 431 pageSize: 10,
 432 
 433 total:0
 434 
 435 };
 436 
 437  
 438 
 439 self.getUserList = function () {
 440 
 441 $http.post('UserManager/List', {
 442 
 443 pageIndex:self.paging.currentPage,
 444 
 445 pageSize: self.paging.pageSize
 446 
 447 })
 448 
 449 .success(function (data, status, headers, config) {
 450 
 451  
 452 
 453 self.userInfo.list.length = 0;
 454 
 455  
 456 
 457 _.forEach(data.AppendData.Data, function (item) {
 458 
 459 self.userInfo.list.push(item);
 460 
 461 });
 462 
 463  
 464 
 465 self.paging.total = data.AppendData.Total;
 466 
 467 
 468 
 469 })
 470 
 471 .error(function (data, status, headers, config) {
 472 
 473 });
 474 
 475 };
 476 
 477 self.createUser = function () {
 478 
 479 return $http.get('UserManager/Create');
 480 
 481 };
 482 
 483  
 484 
 485 self.getUser = function(userid) {
 486 
 487  
 488 
 489 var uow = $q.defer();
 490 
 491  
 492 
 493 $http.post('UserManager/Edit', { id: userid })
 494 
 495 .success(function (data, status, headers, config) {
 496 
 497 uow.resolve(data);
 498 
 499 })
 500 
 501 .error(function (data, status, headers, config) {
 502 
 503 uow.reject(data);
 504 
 505 });
 506 
 507  
 508 
 509 return uow.promise;
 510 
 511  
 512 
 513 };
 514 
 515  
 516 
 517 self.deleteUser = function(userid) {
 518 
 519  
 520 
 521 var uow = $q.defer();
 522 
 523  
 524 
 525 $http.post('UserManager/Delete', { id: userid })
 526 
 527 .success(function (data, status, headers, config) {
 528 
 529 uow.resolve(data);
 530 
 531 })
 532 
 533 .error(function (data, status, headers, config) {
 534 
 535 uow.reject(data);
 536 
 537 });
 538 
 539  
 540 
 541 return uow.promise;
 542 
 543  
 544 
 545 };
 546 
 547  
 548 
 549  
 550 
 551 // 采用promise模式是因为在业务里不处理任何与界面,也就是controller里有关的内容
 552 
 553 self.save = function (user) {
 554 
 555  
 556 
 557 var d = $q.defer();// 创建工作单元
 558 
 559  
 560 
 561 $http.post('UserManager/SaveUser', { userInput: user }).success(function (data, status, headers, config) {
 562 
 563 d.resolve(data);
 564 
 565 }).error(function (data, status, headers, config) {
 566 
 567 d.reject(data);
 568 
 569 });
 570 
 571  
 572 
 573 return d.promise;
 574 
 575 };
 576 
 577  
 578 
 579 return self;
 580 
 581 }]);
 582 
 583  
 584 
 585  
 586 
 587 })();
 588 
 589  
 590 
 591 // #endregion
 592 
 593 
 594 
 595 // #region 用户列表数据处理
 596 
 597 (function () {
 598 
 599 'use strict';
 600 
 601  
 602 
 603 angular
 604 
 605 .module('angle').register
 606 
 607 .controller('DataTableController', DataTableController);
 608 
 609  
 610 
 611 DataTableController.$inject = ['$scope', '$compile', '$modal', '$resource', '$http', 'DTOptionsBuilder', 'DTColumnDefBuilder', 'DTColumnBuilder', 'UserManagerService', 'SweetAlert', 'toaster'];
 612 
 613 function DataTableController($scope, $compile, $modal, $resource, $http, DTOptionsBuilder, DTColumnDefBuilder, DTColumnBuilder, UserManagerService, SweetAlert, toaster) {
 614 
 615 var vm = this;
 616 
 617  
 618 
 619 vm.persons = UserManagerService.userInfo;
 620 
 621  
 622 
 623 activate();
 624 
 625  
 626 
 627 ////////////////
 628 
 629  
 630 
 631 function activate() {
 632 
 633  
 634 
 635 UserManagerService.getUserList();
 636 
 637  
 638 
 639 vm.dtOptions = DTOptionsBuilder.newOptions()
 640 
 641 .withPaginationType('full_numbers') // 分页样式
 642 
 643 .withOption("ordering", false) // 不排序
 644 
 645 .withOption("info", false) // 显示信息
 646 
 647 .withOption("searching", false) // 不允许搜索
 648 
 649 .withOption("paging", false)
 650 
 651 .withLanguage({
 652 
 653 processing: "处理中...",
 654 
 655 lengthMenu: "每页显示 _MENU_ 项结果",
 656 
 657 zeroRecords: "没有匹配结果",
 658 
 659 info: "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项;当前第 _PAGE_页,共 _PAGES_ 页",
 660 
 661 infoEmpty: "显示第 0 至 0 项结果,共 0 项",
 662 
 663 infoFiltered: "(由 _MAX_ 项结果过滤)",
 664 
 665 infoPostFix: "",
 666 
 667 search: "搜索:",
 668 
 669 url: "",
 670 
 671 emptyTable: "表中数据为空",
 672 
 673 loadingRecords: "载入中...",
 674 
 675 infoThousands: ",",
 676 
 677 paginate: {
 678 
 679 first: "首页",
 680 
 681 previous: "上页",
 682 
 683 next: "下页",
 684 
 685 last: "末页"
 686 
 687 },
 688 
 689 oAria: {
 690 
 691 sortAscending: ": 以升序排列此列",
 692 
 693 sortDescending: ": 以降序排列此列"
 694 
 695 }
 696 
 697 }) // 语言
 698 
 699  
 700 
 701 ;
 702 
 703  
 704 
 705 vm.dtColumnDefs = [
 706 
 707 DTColumnDefBuilder.newColumnDef(0).notVisible(),
 708 
 709 DTColumnDefBuilder.newColumnDef(1),
 710 
 711 DTColumnDefBuilder.newColumnDef(2),
 712 
 713 DTColumnDefBuilder.newColumnDef(3)
 714 
 715 ];
 716 
 717  
 718 
 719 }
 720 
 721  
 722 
 723 vm.edit = edit;
 724 
 725 vm.delete = del;
 726 
 727  
 728 
 729 // 编辑用户
 730 
 731 function edit(id) {
 732 
 733 console.log('编辑', id);
 734 
 735  
 736 
 737 UserManagerService.getUser(id).then(function (opresult) {
 738 
 739  
 740 
 741 if (opresult == null) {
 742 
 743 toaster.pop('error', '通知', '返回结果为空');
 744 
 745 return;
 746 
 747 }
 748 
 749  
 750 
 751 if (opresult.ResultType === 0) {
 752 
 753 opDialog(opresult.AppendData);
 754 
 755  
 756 
 757 } else if (opresult.ResultType === 7) {
 758 
 759 toaster.pop('error', '错误', opresult.Message);
 760 
 761 }
 762 
 763  
 764 
 765 });
 766 
 767  
 768 
 769  
 770 
 771 };
 772 
 773  
 774 
 775 // 删除用户
 776 
 777 function del(id) {
 778 
 779 console.log('删除', id);
 780 
 781  
 782 
 783 SweetAlert.swal({
 784 
 785 title: '确定删除吗?',
 786 
 787 text: '删除数据后数据将永久删除,不可撤销',
 788 
 789 type: 'warning',
 790 
 791 showCancelButton: true,
 792 
 793 confirmButtonColor: '#DD6B55',
 794 
 795 confirmButtonText: '确定',
 796 
 797 cancelButtonText: '删除',
 798 
 799 closeOnConfirm: false,
 800 
 801 closeOnCancel: true
 802 
 803 }, function (isConfirm) {
 804 
 805 if (isConfirm) {
 806 
 807  
 808 
 809 UserManagerService.deleteUser(id).then(function(opResult) {
 810 
 811 
 812 
 813 if (opResult.ResultType === 0) {
 814 
 815 SweetAlert.swal(opResult.Message, '', 'success');
 816 
 817 UserManagerService.getUserList();
 818 
 819 }
 820 
 821  
 822 
 823 });
 824 
 825  
 826 
 827 
 828 
 829 }
 830 
 831 });
 832 
 833  
 834 
 835 }
 836 
 837  
 838 
 839 // 对话框操作
 840 
 841 function opDialog(dialogData) {
 842 
 843  
 844 
 845 var modalInstance = $modal.open({
 846 
 847 animation: $scope.animationsEnabled,
 848 
 849 templateUrl: 'myModalContent.html',
 850 
 851 controller: 'ModalInstanceCtrl',
 852 
 853 backdrop: 'static',// 静态
 854 
 855 keyboard: false,// 不能通过esc关闭
 856 
 857 resolve: {
 858 
 859 userInfo: function () {
 860 
 861 return dialogData;//opResult.AppendData;
 862 
 863 }
 864 
 865 }
 866 
 867 });
 868 
 869  
 870 
 871 modalInstance.result.then(function (user) {
 872 
 873  
 874 
 875 UserManagerService.save(user).then(function (opresult) {
 876 
 877  
 878 
 879 if (opresult == null) {
 880 
 881 toaster.pop('error', '通知', '返回结果为空');
 882 
 883 return;
 884 
 885 }
 886 
 887  
 888 
 889 if (opresult.ResultType === 0) {
 890 
 891 toaster.pop('success', '通知', opresult.Message);
 892 
 893 UserManagerService.getUserList();
 894 
 895  
 896 
 897 } else if (opresult.ResultType === 7) {
 898 
 899 toaster.pop('error', '错误', opresult.Message);
 900 
 901 }
 902 
 903  
 904 
 905 });
 906 
 907 }, function () {
 908 
 909 // 取消操作
 910 
 911 });
 912 
 913  
 914 
 915 }
 916 
 917 }
 918 
 919  
 920 
 921 })();
 922 
 923  
 924 
 925 // #endregion
 926 
 927  
 928 
 929 // #region 分页控件的处理
 930 
 931 (function () {
 932 
 933 'use strict';
 934 
 935 angular.module('angle').register.controller('UserPagingController', ['paginationConfig','UserManagerService',
 936 
 937 function (paginationConfig, UserManagerService) {
 938 
 939 var vm = this;
 940 
 941 
 942 
 943 activate();
 944 
 945 ////////////////
 946 
 947  
 948 
 949 function activate() {
 950 
 951  
 952 
 953 vm.paging = UserManagerService.paging;
 954 
 955  
 956 
 957 vm.paging.pageSize = 10;
 958 
 959 vm.pageSizes = [5, 10, 20, 50, 100];
 960 
 961  
 962 
 963 vm.setPage = function (pageNo) {
 964 
 965 vm.paging.currentPage = pageNo;
 966 
 967 };
 968 
 969  
 970 
 971 vm.setNumPages=function() {
 972 
 973 
 974 
 975 }
 976 
 977  
 978 
 979 vm.pageChanged = function () {
 980 
 981 console.log('切换页面到: ' + vm.paging.currentPage);
 982 
 983 UserManagerService.getUserList();
 984 
 985 };
 986 
 987  
 988 
 989 vm.pageSizeChanged = function (pagesize) {
 990 
 991  
 992 
 993 vm.paging.pageSize = pagesize;
 994 
 995 vm.setPage(1);
 996 
 997 vm.pageChanged();
 998 
 999 }
1000 
1001  
1002 
1003 }
1004 
1005 }]);
1006 
1007 })();
1008 
1009 // #endregion
1010 
1011 
1012 
1013 // #region 按钮操作的处理
1014 
1015 (function () {
1016 
1017 'use strict';
1018 
1019  
1020 
1021 var app = angular.module('angle');
1022 
1023 app.register
1024 
1025 .controller('OperationController', ['$scope', '$modal', 'UserManagerService', 'toaster', function ($scope, $modal, UserManagerService, toaster) {
1026 
1027  
1028 
1029 var self = this;
1030 
1031  
1032 
1033 activate();
1034 
1035  
1036 
1037 ////////////////
1038 
1039  
1040 
1041 function activate() {
1042 
1043  
1044 
1045 self.add = function () {
1046 
1047  
1048 
1049 UserManagerService.createUser().then(function success(data) {
1050 
1051  
1052 
1053 var opResult = data.data;
1054 
1055 console.log('data', opResult);
1056 
1057  
1058 
1059 if (opResult == null) {
1060 
1061 return;
1062 
1063 }
1064 
1065  
1066 
1067 if (opResult.ResultType === 0) {
1068 
1069 opDialog(opResult.AppendData);
1070 
1071 }
1072 
1073  
1074 
1075 });
1076 
1077 };
1078 
1079 }
1080 
1081  
1082 
1083 function opDialog(dialogData) {
1084 
1085 
1086 
1087 var modalInstance = $modal.open({
1088 
1089 animation: $scope.animationsEnabled,
1090 
1091 templateUrl: 'myModalContent.html',
1092 
1093 controller: 'ModalInstanceCtrl',
1094 
1095 backdrop: 'static',// 静态
1096 
1097 keyboard: false,// 不能通过esc关闭
1098 
1099 resolve: {
1100 
1101 userInfo: function () {
1102 
1103 return dialogData;//opResult.AppendData;
1104 
1105 }
1106 
1107 }
1108 
1109 });
1110 
1111  
1112 
1113 modalInstance.result.then(function (user) {
1114 
1115  
1116 
1117 UserManagerService.save(user).then(function (opresult) {
1118 
1119  
1120 
1121 console.log('save user opresult ---->', opresult);
1122 
1123 if (opresult == null) {
1124 
1125 toaster.pop('error', '通知', '返回结果为空');
1126 
1127 return;
1128 
1129 }
1130 
1131  
1132 
1133 if (opresult.ResultType === 0) {
1134 
1135 toaster.pop('success', '通知', opresult.Message);
1136 
1137 UserManagerService.getUserList();
1138 
1139  
1140 
1141 } else if (opresult.ResultType === 7) {
1142 
1143 toaster.pop('error', '错误', opresult.Message);
1144 
1145 }
1146 
1147  
1148 
1149 });
1150 
1151 }, function () {
1152 
1153 // 取消操作
1154 
1155 });
1156 
1157  
1158 
1159 }
1160 
1161  
1162 
1163 }]);
1164 
1165  
1166 
1167 // 编辑用户弹出框的controller
1168 
1169 app.register.controller('ModalInstanceCtrl', function ($scope, $modalInstance, userInfo) {
1170 
1171  
1172 
1173 $scope.user = userInfo;
1174 
1175  
1176 
1177 $scope.submitted = false;
1178 
1179  
1180 
1181 $scope.submitForm = function () {
1182 
1183 $scope.submitted = true;
1184 
1185 if ($scope.formValidate.$valid) {
1186 
1187 console.log('Submitted!!');
1188 
1189 $scope.ok();
1190 
1191 return true;
1192 
1193 } else {
1194 
1195 console.log('Not valid!!');
1196 
1197 return false;
1198 
1199 }
1200 
1201  
1202 
1203 };
1204 
1205  
1206 
1207 $scope.validateInput = function (name, type) {
1208 
1209 var input = $scope.formValidate[name];
1210 
1211 return (input.$dirty || $scope.submitted) && input.$error[type];
1212 
1213 };
1214 
1215  
1216 
1217 $scope.ok = function () {
1218 
1219 $modalInstance.close($scope.user);
1220 
1221 };
1222 
1223  
1224 
1225 $scope.cancel = function () {
1226 
1227 $modalInstance.dismiss('cancel');
1228 
1229 };
1230 
1231  
1232 
1233 });
1234 
1235 })();
1236 
1237  
1238 
1239 // #endregion
1240 
1241 
1242 
1243  
1244 
1245 </script>
前端代码

 

 

html结果主要包括了几大部分:搜索、列表操作、列表、分页、通知区域、对话框

相应的,就有对应的几个Controller:SearchController、OperationController、DataTableController、UserPagingController、ModalInstanceCtrl

JS代码中还包括了一部分业务代码,包括了获取、创建、保存等主要业务,代码如下:

  1 (function () {
  2 
  3 'use strict';
  4 
  5  
  6 
  7 angular.module('angle').register.factory('UserManagerService', ['$http', '$q', function ($http, $q) {
  8 
  9 var self = this;
 10 
 11 self.userInfo = {
 12 
 13 list: []
 14 
 15 };
 16 
 17 self.filter = {
 18 
 19 username: ''
 20 
 21 };
 22 
 23  
 24 
 25 self.paging = {
 26 
 27 currentPage: 1,
 28 
 29 pageSize: 10,
 30 
 31 total:0
 32 
 33 };
 34 
 35 // 获取用户列表
 36 
 37 self.getUserList = function () {
 38 
 39 $http.post('UserManager/List', {
 40 
 41 pageIndex:self.paging.currentPage,
 42 
 43 pageSize: self.paging.pageSize
 44 
 45 })
 46 
 47 .success(function (data, status, headers, config) {
 48 
 49  
 50 
 51 self.userInfo.list.length = 0;
 52 
 53  
 54 
 55 _.forEach(data.AppendData.Data, function (item) {
 56 
 57 self.userInfo.list.push(item);
 58 
 59 });
 60 
 61  
 62 
 63 self.paging.total = data.AppendData.Total;
 64 
 65 
 66 
 67 })
 68 
 69 .error(function (data, status, headers, config) {
 70 
 71 });
 72 
 73 };
 74 
 75  
 76 
 77 // 创建用户
 78 
 79 self.createUser = function () {
 80 
 81 return $http.get('UserManager/Create');
 82 
 83 };
 84 
 85  
 86 
 87 // 获取用户
 88 
 89 self.getUser = function(userid) {
 90 
 91  
 92 
 93 var uow = $q.defer();
 94 
 95  
 96 
 97 $http.post('UserManager/Edit', { id: userid })
 98 
 99 .success(function (data, status, headers, config) {
100 
101 uow.resolve(data);
102 
103 })
104 
105 .error(function (data, status, headers, config) {
106 
107 uow.reject(data);
108 
109 });
110 
111  
112 
113 return uow.promise;
114 
115  
116 
117 };
118 
119  
120 
121 // 删除用户
122 
123 self.deleteUser = function(userid) {
124 
125  
126 
127 var uow = $q.defer();
128 
129  
130 
131 $http.post('UserManager/Delete', { id: userid })
132 
133 .success(function (data, status, headers, config) {
134 
135 uow.resolve(data);
136 
137 })
138 
139 .error(function (data, status, headers, config) {
140 
141 uow.reject(data);
142 
143 });
144 
145  
146 
147 return uow.promise;
148 
149  
150 
151 };
152 
153  
154 
155  
156 
157 // 采用promise模式是因为在业务里不处理任何与界面,也就是controller里有关的内容
158 
159 // 保存用户
160 
161 self.save = function (user) {
162 
163  
164 
165 var d = $q.defer();// 创建工作单元
166 
167  
168 
169 $http.post('UserManager/SaveUser', { userInput: user }).success(function (data, status, headers, config) {
170 
171 d.resolve(data);
172 
173 }).error(function (data, status, headers, config) {
174 
175 d.reject(data);
176 
177 });
178 
179  
180 
181 return d.promise;
182 
183 };
184 
185  
186 
187 return self;
188 
189 }]);
190 
191  
192 
193  
194 
195 })();
196 
197  
js用户业务代码

 

DataTableController 处的代码主要是控制用户列表的显示,使用的是angular 下的datatables的插件

UserPagingController 主要是负责分页区域的逻辑控制 。

在使用angularjs中,由于并不是一次性加载所有逻辑文件到浏览器中,所以在网上找到了一段扩展的代码 app.register来延迟定义controller、factory等功能,此处代码放在后文,在写angle时会单独提出来说明。

 

3.2 后台代码

在3.1中,angular通过使用factory定义了一个业务,每个业务调用对应的访问地址获取后台数据。

对应的控制器代码如下:

 

  1 /// <summary>
  2 
  3 /// The user manager controller.
  4 
  5 /// </summary>
  6 
  7 [NeedLogined]
  8 
  9 [SystemModel("用户管理")]
 10 
 11 public class UserManagerController : Controller
 12 
 13 {
 14 
 15 /// <summary>
 16 
 17 /// The user service.
 18 
 19 /// </summary>
 20 
 21 private readonly IUserService userService;
 22 
 23  
 24 
 25 /// <summary>
 26 
 27 /// Initializes a new instance of the <see cref="UserManagerController"/> class.
 28 
 29 /// </summary>
 30 
 31 /// <param name="userService">
 32 
 33 /// The user service.
 34 
 35 /// </param>
 36 
 37 public UserManagerController(IUserService userService)
 38 
 39 {
 40 
 41 this.userService = userService;
 42 
 43 }
 44 
 45  
 46 
 47 /// <summary>
 48 
 49 /// The index.
 50 
 51 /// </summary>
 52 
 53 /// <returns>
 54 
 55 /// The <see cref="ActionResult"/>.
 56 
 57 /// </returns>
 58 
 59 public ActionResult Index()
 60 
 61 {
 62 
 63 return this.RedirectToAction("List");
 64 
 65 }
 66 
 67  
 68 
 69 /// <summary>
 70 
 71 /// The list.
 72 
 73 /// </summary>
 74 
 75 /// <returns>
 76 
 77 /// The <see cref="ActionResult"/>.
 78 
 79 /// </returns>
 80 
 81 [PermissionSetting(PermissionValue.Lookup)]
 82 
 83 public ActionResult List()
 84 
 85 {
 86 
 87 return this.View();
 88 
 89 }
 90 
 91  
 92 
 93 /// <summary>
 94 
 95 /// The search list.
 96 
 97 /// </summary>
 98 
 99 /// <returns>
100 
101 /// The <see cref="JsonResult"/>.
102 
103 /// </returns>
104 
105 [HttpPost]
106 
107 [ActionName("List")]
108 
109 public JsonResult SearchList(int pageIndex =1,int pageSize = 10)
110 
111 {
112 
113 var total = 0;
114 
115  
116 
117 var userList = this.userService.GetAllUser(pageIndex, pageSize, out total);
118 
119  
120 
121 return
122 
123 this.Json(
124 
125 OperationResult.Success(
126 
127 string.Empty,
128 
129 string.Empty,
130 
131 new { Total = total, PageSize = pageSize, Data = userList }));
132 
133 }
134 
135  
136 
137 /// <summary>
138 
139 /// 获取新用户,若要对新增功能进行控制,则必须添加一个httpget方法才行
140 
141 /// </summary>
142 
143 /// <returns>
144 
145 /// The <see cref="ActionResult"/>.
146 
147 /// </returns>
148 
149 [PermissionSetting(PermissionValue.Create)]
150 
151 public ActionResult Create()
152 
153 {
154 
155 var newUser = new EditUserInputDto();
156 
157 return this.Json(OperationResult.Success(string.Empty, string.Empty, newUser),JsonRequestBehavior.AllowGet);
158 
159 }
160 
161  
162 
163 /// <summary>
164 
165 /// The create post.
166 
167 /// </summary>
168 
169 /// <param name="userInput">
170 
171 /// The user input.
172 
173 /// </param>
174 
175 /// <returns>
176 
177 /// The <see cref="ActionResult"/>.
178 
179 /// </returns>
180 
181 [HttpPost]
182 
183 public ActionResult SaveUser(EditUserInputDto userInput)
184 
185 {
186 
187 try
188 
189 {
190 
191 if (userInput.Id == Guid.Empty)
192 
193 {
194 
195 this.userService.Add(userInput);
196 
197 }
198 
199 else
200 
201 {
202 
203 this.userService.Update(userInput);
204 
205 }
206 
207  
208 
209 return this.Json(OperationResult.Success("保存成功"));
210 
211 }
212 
213 catch (Exception e)
214 
215 {
216 
217 return this.Json(OperationResult.Error("保存失败," + e.Message));
218 
219 }
220 
221 }
222 
223  
224 
225 /// <summary>
226 
227 /// The edit.
228 
229 /// </summary>
230 
231 /// <param name="id">
232 
233 /// The id.
234 
235 /// </param>
236 
237 /// <returns>
238 
239 /// The <see cref="ActionResult"/>.
240 
241 /// </returns>
242 
243 [PermissionSetting(PermissionValue.Edit)]
244 
245 public ActionResult Edit(Guid id)
246 
247 {
248 
249 var user = this.userService.GetUserById(id);
250 
251 return this.Json(OperationResult.Success(string.Empty,string.Empty,user));
252 
253 }
254 
255  
256 
257 /// <summary>
258 
259 /// The delete.
260 
261 /// </summary>
262 
263 /// <param name="id">
264 
265 /// The id.
266 
267 /// </param>
268 
269 /// <returns>
270 
271 /// The <see cref="ActionResult"/>.
272 
273 /// </returns>
274 
275 [PermissionSetting(PermissionValue.Delete)]
276 
277 public ActionResult Delete(Guid id)
278 
279 {
280 
281 this.userService.Delete(id);
282 
283 return this.Json(OperationResult.Success("删除成功"));
284 
285 }
286 
287 }
用户管理控制器

 

 

所有的Action操作都比较简单,就是直接调用Service层代码

对应的UesrService使用代码如下:

  1 /// <summary>
  2 
  3 /// 用户服务实现
  4 
  5 /// </summary>
  6 
  7 public class UserService:IUserService
  8 
  9 {
 10 
 11 /// <summary>
 12 
 13 /// 用户仓储
 14 
 15 /// </summary>
 16 
 17 private readonly IUserRepository userRepository;
 18 
 19  
 20 
 21 /// <summary>
 22 
 23 /// Initializes a new instance of the <see cref="UserService"/> class.
 24 
 25 /// </summary>
 26 
 27 /// <param name="userRepository">
 28 
 29 /// The user repository.
 30 
 31 /// </param>
 32 
 33 public UserService(IUserRepository userRepository)
 34 
 35 {
 36 
 37 this.userRepository = userRepository;
 38 
 39 }
 40 
 41  
 42 
 43 /// <summary>
 44 
 45 /// The add.
 46 
 47 /// </summary>
 48 
 49 /// <param name="userInput">
 50 
 51 /// The user input.
 52 
 53 /// </param>
 54 
 55 public void Add(EditUserInputDto userInput)
 56 
 57 {
 58 
 59 Guard.ArgumentNotNull(() => userInput);
 60 
 61 var toAdd = Mapper.Map<User>(userInput);
 62 
 63  
 64 
 65 using (var uof = EngineContext.Current.Resolve<ISkymateUnitOfWork>())
 66 
 67 {
 68 
 69 if (toAdd.ID == Guid.Empty)
 70 
 71 {
 72 
 73 toAdd.ID = Guid.NewGuid();
 74 
 75 }
 76 
 77  
 78 
 79 this.userRepository.Add(toAdd);
 80 
 81 uof.Commit();
 82 
 83 }
 84 
 85 }
 86 
 87  
 88 
 89 /// <summary>
 90 
 91 /// The update.
 92 
 93 /// </summary>
 94 
 95 /// <param name="userInput">
 96 
 97 /// The user input.
 98 
 99 /// </param>
100 
101 public void Update(EditUserInputDto userInput)
102 
103 {
104 
105 Guard.ArgumentNotNull(() => userInput);
106 
107 Guard.ArgumentNotEmpty(() => userInput.Id);
108 
109  
110 
111 var toUpdate = this.userRepository.GetByKey(userInput.Id);
112 
113  
114 
115 toUpdate = Mapper.Map<EditUserInputDto, User>(userInput, toUpdate);
116 
117 this.userRepository.Update(toUpdate);
118 
119 this.userRepository.Context.Commit();
120 
121 }
122 
123  
124 
125 /// <summary>
126 
127 /// The delete.
128 
129 /// </summary>
130 
131 /// <param name="userid">
132 
133 /// The userid.
134 
135 /// </param>
136 
137 public void Delete(Guid userid)
138 
139 {
140 
141 Guard.ArgumentNotEmpty(() => userid);
142 
143  
144 
145 var toRemove = this.userRepository.GetByKey(userid);
146 
147 this.userRepository.Remove(toRemove);
148 
149 this.userRepository.Context.Commit();
150 
151 }
152 
153  
154 
155 /// <summary>
156 
157 /// The get user by id.
158 
159 /// </summary>
160 
161 /// <param name="userid">
162 
163 /// The userid.
164 
165 /// </param>
166 
167 /// <returns>
168 
169 /// The <see cref="EditUserInputDto"/>.
170 
171 /// </returns>
172 
173 public EditUserInputDto GetUserById(Guid userid)
174 
175 {
176 
177 Guard.ArgumentNotEmpty(() => userid);
178 
179  
180 
181 var user = this.userRepository.GetByKey(userid);
182 
183 return Mapper.Map<EditUserInputDto>(user);
184 
185 }
186 
187  
188 
189 /// <summary>
190 
191 /// The get all user.
192 
193 /// </summary>
194 
195 /// <param name="pageIndex">
196 
197 /// The page index.
198 
199 /// </param>
200 
201 /// <param name="pageSize">
202 
203 /// The page size.
204 
205 /// </param>
206 
207 /// <param name="total">
208 
209 /// The total.
210 
211 /// </param>
212 
213 /// <returns>
214 
215 /// The <see cref="IEnumerable"/>.
216 
217 /// </returns>
218 
219 /// <exception cref="Exception">
220 
221 /// </exception>
222 
223 public IEnumerable<UserListOutputDto> GetAllUser(int pageIndex, int pageSize, out int total)
224 
225 {
226 
227 Guard.ArgumentInRange<int>(pageIndex, 0, int.MaxValue, "pageIndex");
228 
229 
230 
231 var query = this.userRepository.FindAll();
232 
233  
234 
235 total = query.Count();
236 
237 query = query.OrderBy(u => u.UserName).Skip((pageIndex - 1) * pageSize).Take(pageSize);
238 
239  
240 
241 return query.ToList().Select(Mapper.Map<UserListOutputDto>);
242 
243 }
244 
245 }
用户业务

 

代码中并没有使用检索功能,所有的代码亦比较简单,就是简单的增删改查!

 

4.总结

    本章主要介绍了用户管理模块的前端代码和后端代码的内容,还有相关的功能并未实现,比如添加/编辑用户的时候没有对用户组的操作、查询中并没有检索功能等等,这些功能会在后面的代码中补全。

    本章内容依然使用了mvc中的访问控制器中的内容来获取数据,计划在写完博客只会,研究使用webapi提供数据服务,这样就可以使用mvc的控制器负责页面跳转,webapi提供数据,js/html负责展示数据,做到前后端分离。

----------------------------------------------------------------------------------------------

推荐QQ群:

278252889(AngularJS中文社区)

5008599(MVC EF交流群)

134710707(ABP架构设计交流群 )

59557329(c#基地 )

230516560(.NET DDD基地 )

本人联系方式:QQ:351157970

posted @ 2015-11-09 15:57  诸葛小亮  阅读(2119)  评论(5编辑  收藏  举报