ASP.NET Core+Element+SQL Server开发校园图书管理系统(二)

随着技术的进步,跨平台开发已经成为了标配,在此大背景下,ASP.NET Core也应运而生。本文主要基于ASP.NET Core+Element+Sql Server开发一个校园图书管理系统为例,简述基于MVC三层架构开发的常见知识点,前一篇文章,已经简单介绍了如何搭建开发框架,和登录功能实现,本篇文章继续讲解主页面的开发,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

在本示例中,应用最多的就是如何Element中提供的组件,和控制器中业务逻辑处理,涉及知识点如下所示:

  • MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式,其中Controller(控制器)处理输入(写入数据库记录)。控制器Controller,是应用程序中处理用户交互的部分,通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。
  • Element组件库,一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库。可以大大提高开发效率,减少工作量。在主页面中,主要用到如下几种:
    • 容器布局el-container组件,用于布局的容器组件,主要包含:<el-header>:顶栏容器。<el-aside>:侧边栏容器。<el-main>:主要区域容器。<el-footer>:底栏容器。可以进行不同组合,布局出管理系统通用页面(如,上中下结构,上(左右)下结构等)。
    • 导航菜单el-menu组件,为网站提供导航功能的菜单。有顶栏,侧栏,折叠等不同用法。
  • axios组件,是一个基于promise 的网络请求库,axios本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范。在本示例中,所有的前后端交互,均是通过axios库。

核心源码

1. 组件引入

因为使用了Element提供的组件,大大节约了工作量,可以专注于业务逻辑的处理。引入组件库也非常简单,在客户端库安装以后【具体安装可参考前一篇文章】,直接在视图中进行引用即可,如下所示:

 1 <head>
 2     <title>校园图书管理系统</title>
 3     <!-- For-Mobile-Apps-and-Meta-Tags -->
 4     <meta name="viewport" content="width=device-width, initial-scale=1" />
 5     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 6     
 7     <!-- 引入样式 -->
 8     <link rel="stylesheet" href="/lib/element-ui/theme-chalk/index.min.css">
 9     <!-- 引入组件库 -->
10     <script src="/lib/vue/dist/vue.min.js"></script>
11     <script src="/lib/element-ui/index.min.js"></script>
12     <script src="/lib/axios/axios.min.js"></script>
13 </head>

2. 页面布局

页面布局采用el-container,代码结构清晰明了,易于理解,如下所示:

 1 <div id="app">
 2     <el-container style="height:100vh; margin:0px;">
 3       <el-header style="background:url('/imgs/banner.jpg');height:120px;">
 4           <h1>
 5               校园图书管理系统  Campus Library Management System
 6           </h1>
 7           <div style="text-align:right;position:relative;bottom:30px;">
 8               <el-link type="info" style="color:white;" href="/Home/Welcome" target="content">首页</el-link>|
 9               <el-link type="info" style="color:white;" href="/Personal"  target="content">{{nickName}}</el-link>|
10               <el-link type="info" style="color:white;">退出</el-link>
11           </div>
12       </el-header>
13       <el-container>
14         <el-aside width="200px">
15             <el-menu
16               default-active="activeIndex"
17               class="el-menu-vertical-demo"
18               v-on:open="handleOpen"
19               v-on:close="handleClose"
20               v-on:select="handleSelect"
21               background-color="#545c64"
22               text-color="#fff"
23               active-text-color="#ffd04b">
24               <el-submenu :index="index" v-for="(right,index) in rights">
25                 <template slot="title">
26                   <span>{{right.menuName}}</span>
27                 </template>
28                 <el-menu-item index="1-1" v-for="(menu,index) in right.Menus">
29                     <el-link type="primary" underline="false" :href="menu.url" target="content">{{menu.menuName}}</el-link>
30                 </el-menu-item>
31               </el-submenu>
32             </el-menu>
33         </el-aside>
34         <el-container>
35           <el-main name="main" style="padding:0px;">
36               <iframe name="content" id="content" style="border:0px;width:100%;height:100%;margin:0px;background:white; padding:0px;" src="/Home/Welcome">
37                   
38               </iframe>
39           </el-main>
40           <el-footer style="background:#409EFF;">
41               <p style="color:white;"> &copy; 2022-2023 校园图书管理系统. All Rights Reserved | Design by 小六公子</p>
42           </el-footer>
43         </el-container>
44       </el-container>
45     </el-container>
46 </div>

3. 数据交互

数据交互通过JS脚本进行,书写格式和VUE2.0保持一致,在页面启动时,加载用户所拥有的导航菜单,并绑定到el-menu对象,所以需要在mounted函数中增加调用向服务器端发出请求,如下所示:

 1 <script>
 2    var app= new Vue({
 3         el: '#app',
 4         data:function() {
 5           return {
 6             activeIndex:'/',
 7             rights:[],
 8             nickName:'',
 9           }
10         },
11         mounted:function(){
12             this.handleLoadInfo();
13             this.handleLoadRights();
14         },
15         methods: {
16           handleOpen(key, keyPath) {
17             console.log(key, keyPath);
18           },
19           handleClose(key, keyPath) {
20             console.log(key, keyPath);
21           },
22           handleSelect(index,indexPath){
23             this.activeIndex=index;
24             console.log("index="+index+",indexPath="+indexPath);
25           },
26           handleLoadRights(){
27             var that = this;
28             that.rights=[];
29             console.log("query");
30             axios.get('/Home/GetUserRights', {params:{}}).then(function (response) {
31                 if(response.status==200){
32                     var data = response.data;
33                     let parentMenus=data.filter(function(e){
34                         return e.parentId==null;
35                     });
36                     for(let index=0;index< parentMenus.length;index++){
37                         let parentMenu=parentMenus[index];
38                         let pId=parentMenu.id;
39                         console.log(pId);
40                         let menus = data.filter(function(e){
41                             return e.parentId==pId;
42                         });
43                         console.log(menus);
44                         parentMenu.Menus=menus;
45                         that.rights.push(parentMenu);
46                     }
47                     console.log(that.rights);
48                 }
49                 console.log(response);
50             }).catch(function (error) {
51                 console.log(error);
52             });
53           },
54           handleLoadInfo(){
55             var that =this;
56             axios.get('/User/GetPersonalInfo', {params:{}}).then(function (response) {
57                 if(response.status==200){
58                     var data = response.data;
59                     that.nickName=data.nickName;
60                 }
61                 console.log(response);
62             }).catch(function (error) {
63                 console.log(error);
64             });
65           }
66         }
67       });
68 </script>

4. 控制器逻辑

主页面控制器【HomeCotroller】逻辑主要通过登录的ID,获取对应的权限菜单,然后返回给客户端,如下所示:

 1 namespace CLMS.Controllers
 2 {
 3     public class HomeController : Controller
 4     {
 5         private readonly ILogger<HomeController> _logger;
 6 
 7         private DataContext dataContext;
 8 
 9         public HomeController(ILogger<HomeController> logger, DataContext context)
10         {
11             _logger = logger;
12             dataContext = context;
13         }
14 
15         public IActionResult Index()
16         {
17             int? userId = HttpContext.Session.GetInt32("UserId");
18             //判断是否登录
19             if (userId != null)
20             {
21 
22                 var user = dataContext.Users.FirstOrDefault(u => u.Id == userId);
23                 if (user != null)
24                 {
25                     ViewBag.NickName = user.NickName;
26                     ViewBag.UserRights = GetUserRights();
27                 }
28                 return View();
29             }
30             else
31             {
32                 return Redirect("/Login");
33             }
34 
35         }
36 
37         public IActionResult Welcome()
38         {
39             return View();
40         }
41 
42         [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
43         public IActionResult Error()
44         {
45             return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
46         }
47 
48         [HttpGet]
49         public List<UserRight> GetUserRights()
50         {
51             int? userId = HttpContext.Session.GetInt32("UserId");
52             if (userId != null)
53             {
54                 var query = from u in dataContext.UserRoles
55                             join r in dataContext.Roles on u.RoleId equals r.Id
56                             join x in dataContext.RoleMenus on r.Id equals x.RoleId
57                             join m in dataContext.Menus on x.MenuId equals m.Id
58                             where u.UserId == userId
59                             select new UserRight { Id = m.Id, RoleName = r.Name, MenuName = m.Name, Url = m.Url, ParentId = m.ParentId, SortId = m.SortId };
60 
61                 return query.ToList();
62             }
63             return null;
64         }
65 
66         /// <summary>
67         /// 退出
68         /// </summary>
69         public IActionResult Logout()
70         {
71             HttpContext.Session.Clear();
72             return Redirect("/Login");
73         }
74     }
75 }

运行测试

导航菜单主要分为图书管理,书室管理,系统管理三大块,可以折叠展开。主页面开发完成后,运行测试。如下所示:

 

以上就是校园图书管理系统的主页面功能实现,功能正在开发完善中,后续功能再继续介绍。旨在抛砖引玉,一起学习,共同进步。

posted @ 2023-01-26 22:04  老码识途呀  阅读(603)  评论(1编辑  收藏  举报