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

<head>
    <title>校园图书管理系统</title>
    <!-- For-Mobile-Apps-and-Meta-Tags -->
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <!-- 引入样式 -->
    <link rel="stylesheet" href="/lib/element-ui/theme-chalk/index.min.css">
    <!-- 引入组件库 -->
    <script src="/lib/vue/dist/vue.min.js"></script>
    <script src="/lib/element-ui/index.min.js"></script>
    <script src="/lib/axios/axios.min.js"></script>
</head>

2. 页面布局

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

<div id="app">
    <el-container style="height:100vh; margin:0px;">
      <el-header style="background:url('/imgs/banner.jpg');height:120px;">
          <h1>
              校园图书管理系统  Campus Library Management System
          </h1>
          <div style="text-align:right;position:relative;bottom:30px;">
              <el-link type="info" style="color:white;" href="/Home/Welcome" target="content">首页</el-link>|
              <el-link type="info" style="color:white;" href="/Personal"  target="content">{{nickName}}</el-link>|
              <el-link type="info" style="color:white;">退出</el-link>
          </div>
      </el-header>
      <el-container>
        <el-aside width="200px">
            <el-menu
              default-active="activeIndex"
              class="el-menu-vertical-demo"
              v-on:open="handleOpen"
              v-on:close="handleClose"
              v-on:select="handleSelect"
              background-color="#545c64"
              text-color="#fff"
              active-text-color="#ffd04b">
              <el-submenu :index="index" v-for="(right,index) in rights">
                <template slot="title">
                  <span>{{right.menuName}}</span>
                </template>
                <el-menu-item index="1-1" v-for="(menu,index) in right.Menus">
                    <el-link type="primary" underline="false" :href="menu.url" target="content">{{menu.menuName}}</el-link>
                </el-menu-item>
              </el-submenu>
            </el-menu>
        </el-aside>
        <el-container>
          <el-main name="main" style="padding:0px;">
              <iframe name="content" id="content" style="border:0px;width:100%;height:100%;margin:0px;background:white; padding:0px;" src="/Home/Welcome">

              </iframe>
          </el-main>
          <el-footer style="background:#409EFF;">
              <p style="color:white;"> © 2022-2023 校园图书管理系统. All Rights Reserved | Design by 小六公子</p>
          </el-footer>
        </el-container>
      </el-container>
    </el-container>
</div>

3. 数据交互

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

<script>
   var app= new Vue({
        el: '#app',
        data:function() {
          return {
            activeIndex:'/',
            rights:[],
            nickName:'',
          }
        },
        mounted:function(){
            this.handleLoadInfo();
            this.handleLoadRights();
        },
        methods: {
          handleOpen(key, keyPath) {
            console.log(key, keyPath);
          },
          handleClose(key, keyPath) {
            console.log(key, keyPath);
          },
          handleSelect(index,indexPath){
            this.activeIndex=index;
            console.log("index="+index+",indexPath="+indexPath);
          },
          handleLoadRights(){
            var that = this;
            that.rights=[];
            console.log("query");
            axios.get('/Home/GetUserRights', {params:{}}).then(function (response) {
                if(response.status==200){
                    var data = response.data;
                    let parentMenus=data.filter(function(e){
                        return e.parentId==null;
                    });
                    for(let index=0;index< parentMenus.length;index++){
                        let parentMenu=parentMenus[index];
                        let pId=parentMenu.id;
                        console.log(pId);
                        let menus = data.filter(function(e){
                            return e.parentId==pId;
                        });
                        console.log(menus);
                        parentMenu.Menus=menus;
                        that.rights.push(parentMenu);
                    }
                    console.log(that.rights);
                }
                console.log(response);
            }).catch(function (error) {
                console.log(error);
            });
          },
          handleLoadInfo(){
            var that =this;
            axios.get('/User/GetPersonalInfo', {params:{}}).then(function (response) {
                if(response.status==200){
                    var data = response.data;
                    that.nickName=data.nickName;
                }
                console.log(response);
            }).catch(function (error) {
                console.log(error);
            });
          }
        }
      });
</script>

4. 控制器逻辑

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

namespace CLMS.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private DataContext dataContext;

        public HomeController(ILogger<HomeController> logger, DataContext context)
        {
            _logger = logger;
            dataContext = context;
        }

        public IActionResult Index()
        {
            int? userId = HttpContext.Session.GetInt32("UserId");
            //判断是否登录
            if (userId != null)
            {

                var user = dataContext.Users.FirstOrDefault(u => u.Id == userId);
                if (user != null)
                {
                    ViewBag.NickName = user.NickName;
                    ViewBag.UserRights = GetUserRights();
                }
                return View();
            }
            else
            {
                return Redirect("/Login");
            }

        }

        public IActionResult Welcome()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpGet]
        public List<UserRight> GetUserRights()
        {
            int? userId = HttpContext.Session.GetInt32("UserId");
            if (userId != null)
            {
                var query = from u in dataContext.UserRoles
                            join r in dataContext.Roles on u.RoleId equals r.Id
                            join x in dataContext.RoleMenus on r.Id equals x.RoleId
                            join m in dataContext.Menus on x.MenuId equals m.Id
                            where u.UserId == userId
                            select new UserRight { Id = m.Id, RoleName = r.Name, MenuName = m.Name, Url = m.Url, ParentId = m.ParentId, SortId = m.SortId };

                return query.ToList();
            }
            return null;
        }

        /// <summary>
        /// 退出
        /// </summary>
        public IActionResult Logout()
        {
            HttpContext.Session.Clear();
            return Redirect("/Login");
        }
    }
}

运行测试

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老码识途呀

写作不易,多谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值