C#MVC 进销存项目

C#MVC 进销存项目
1、项目概要
2、数据库设计
2.1 数据表
2.2 业务表及其字段
3、设计与实现
3.1 业务功能 1 名称:进货管理.
3.1-1 功能实现.
3.1-2 表和关系.
3.1-2 经典代码
3.2 业务功能 2 名称:销售管理.
3.2-1 功能实现
3.2-2 表和关系
3.2-2 经典代码
3.3 业务功能 3 名称:往来账务
3.3-1 功能实现
3.3-2 表和关系
3.3-2 经典代码
3.4 基础数据功能 4 名称:权限管理
3.41 功能实现
4、技术总结
1、项目概要
(说明:用 500 字左右,对所做项目整体功能进行描述,并描绘出功能架构图)
系统主要功能模块有:
(1)系统管理。主要包括添加商品、密码修改、添加供货商、添加客户、添加部门、添加员工、添加操作员、添加角色、权限设置、账号管理、打印设置、参数设置的功能
(2)基础信息。主要包括使用单位、供货商类别、客户类别、仓库类别、常用数据字典、商品类别、付款方式、支付类型
(3)进货管理。主要包括采购进货,采购退货,采购入库,生产入库,往来账务,采购入库查询,该页面操作,把需要采购的商品选中出来,保存进货单,审核进货单,查看进货明细。
(4)销售管理。主要包括商品销售,顾客退货,商品销售查询,部门领用,部门退回,该页面大致与进货略同,都是把需要销售的商品选择出来,保存销售单,审核销售单,查看销售明细。顾客退货,部门领用,部门退回,操作与商品销售一样。
(5)库存管理。主要包括库存盘点,库存调拨,库存报警。
(6)统计报表。主要包括进销存明细,进销存汇总,收货对账单,发货对账单,发货成本,销售毛利该页面就是统计页面,把数据进行汇总查询。
(7)往来账款。主要包括应收登记,收款登记,应付账表,应付登记,付款登记,应付账表
2、数据库设计
(说明:列出整个数据库表名;业务数据表的字段清单)
2.1 数据表
SN 数据表 描述

1 B_AccountsPayable 供货单:应付账表
2 B_DepartmentChange 部门领用,退回
3 B_DepartmentChangeDetail 部门领用,退回明细
4 B_InventoryChange 库存变动:商品库存变动记录表
5 B_Purchase 采购进货,退货
6 B_PurchaseDetail 采购进货,退货明细
7 B_ReceivableBill 客户:应收账表
8 B_RegistrationForm 客户:应收,收款登记表
9 B_Sales 商品销售,退货
10 B_SalesDetail 商品销售,退货明细
11 B_SupplierRegistrationBill 供应商:应付,付款登记表
12 B_WarehouseChange 仓库:库存调拨,盘点表
13 B_WarehouseChangeDetail 仓库:库存调拨,盘点明细表
14 D_City 城市表
15 D_District 地区表
16 D_Province 省份表
17 R_Permission 权限表
18 R_Repertory 库存表
19 S_CommoditiesUnit 商品单位表
20 S_Customer 客户表
21 S_CustomerType 客户类别表
22 S_Department 部门表
23 S_Employee 员工表
24 S_Module 模块表
25 S_Operator 操作员表
26 S_PaymentMethod 支付类型表
27 S_Product 商品表
28 S_ProductCategory 商品类别表
29 S_Role 角色表
30 S_Supplier 供货商表
31 S_SupplierType 供货商类别表
32 S_Warehouse 仓库表
2.2 业务表及其字段

B_AccountsPayable 供货单:应付账表

数据表名称 B_AccountsPayable 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 accountsPayableID int identity (10, 0) NO PK 应付账 ID
2 supplierID int (10, 0) YES 供应商 ID
3 payableNo nvarchar 30 YES 单据号
4 billingDate datetime (23, 3) YES 开单日期
5 paymentMethodID int (10, 0) YES 付款方式 ID
6 type nvarchar 30 YES 单据类型
7 beginPay decimal (8, 2) YES 期初应付
8 currentPay decimal (8, 2) YES 本期应付
9 currentPrepaid decimal (8, 2) YES 本期已付
10 endPay decimal (8, 2) YES 期末应付
11 remarks nvarchar 200 YES 备注

B_DepartmentChange 部门领用,退回

数据表名称 B_DepartmentChange 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 departmentChangeID int identity (10, 0) NO PK 部门领用 ID
2 dChangeNo nvarchar 30 YES 单号
3 departmentID int (10, 0) YES 领用/退回部门 ID
4 warehouseID int (10, 0) YES 领用/退回仓库 ID
5 billingDate datetime (23, 3) YES 开单日期
6 barCode nvarchar 30 YES 条码
7 totalAmount decimal (8, 2) YES 总金额
8 agentID int (10, 0) YES 经办人 ID
9 remark nvarchar 200 YES 备注
10 type nvarchar 30 YES 类型
11 reviewWhether bit 1 YES 审核否
12 reviewerID int (10, 0) YES 审核人 ID
13 auditDate datetime (23, 3) YES 审核日期

B_DepartmentChangeDetail 数据表描述

SN 字段 数据型态 长度 null PK 描述
1 dChangeDetailID int identity (10, 0) NO PK 明细 ID
2 departmentChangeID int (10, 0) YES 部门领用 ID
3 productID int (10, 0) YES 商品 ID
4 quantity int (10, 0) YES 数量
5 totalCost decimal (8, 2) YES 总成本
6 remark nvarchar 200 YES 备注

B_InventoryChange 库存变动:商品库存变动记录表

数据表名称 B_InventoryChange 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 inventoryChangeID int identity (10, 0) NO PK 库存变动 ID
2 changeDate datetime (23, 3) YES 日期
3 chageNo nvarchar 30 YES 单据号
4 describe nvarchar 50 YES 说明
5 person nvarchar 30 YES 供应商/客户
6 warehousingNumber int (10, 0) YES 入库数
7 outboundNumber int (10, 0) YES 出库数
8 unitPrice decimal (8, 2) YES 单价
9 totalAmount decimal (8, 2) YES 总金额
10 repertoryID int (10, 0) YES 库存 ID
11 handlerID int (10, 0) YES 经办人 ID
12 operatorID int (10, 0) YES 操作员 ID

B_Purchase 采购进货,退货

**数据表名称 B_Purchase 数据表描述**
SN 字段 数据型态 长度 null PK 描述
1 purchaseID int identity (10, 0) NO PK 往来 ID
2 OrderNo nvarchar 30 YES 单号
3 supplierID int (10, 0) YES 供应商 ID
4 warehouseID int (10, 0) YES 收货仓库 ID
5 receiptDate datetime (23, 3) YES 收货日期
6 barCode nvarchar 30 YES 条码
7 amountPayable decimal (8, 2) YES 应付金额
8 realPay decimal (8, 2) YES 实付金额
9 amountsOwed decimal (8, 2) YES 欠款金额
10 discountAmount decimal (8, 2) YES 优惠金额
11 paymentMethodID int (10, 0) YES 付款方式 ID
12 agentID int (10, 0) YES 经办人 ID
13 remark nvarchar 200 YES 备注
14 type nvarchar 20 YES 类型
15 reviewWhether bit 1 YES 审核否
16 reviewerID int (10, 0) YES 审核人 ID
17 auditDate datetime (23, 3) YES 审核日期

B_PurchaseDetail 采购进货,退货明细

数据表名称 B_PurchaseDetail 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 purchaseDetailID int identity (10, 0) NO PK 往来明细 ID
2 purchaseID int (10, 0) YES 往来 ID
3 productID int (10, 0) YES 商品 ID
4 purchasingPrice decimal (8, 2) YES 采购单价
5 discount decimal (5, 2) YES 折扣
6 discountPrice decimal (8, 2) YES 折后价
7 quantity int (10, 0) YES 数量
8 totalAmount decimal (8, 2) YES 总金额
9 remark nvarchar 200 YES 备注
```**加粗样式**
**B_ReceivableBill 客户:应收账表**
```csharp
数据表名称 B_ReceivableBill 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 receivableBillID int identity (10, 0) NO PK 应收账 ID
2 customerID int (10, 0) YES 客户 ID
3 billNo nvarchar 30 YES 单据号
4 billingDate datetime (23, 3) YES 开单日期
5 paymentMethodID int (10, 0) YES 收款方式 ID
6 type nvarchar 30 YES 单据类型
7 beginReceivable decimal (8, 2) YES 期初应收
8 currentReceivable decimal (8, 2) YES 本期应收
9 currentReceived decimal (8, 2) YES 本期已收
10 endReceivable decimal (8, 2) YES 期末应收
11 remarks nvarchar 200 YES 备注

B_RegistrationForm 客户:应收,收款登记表

数据表名称 B_RegistrationForm 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 registrationFormID int identity (10, 0) NO PK 登记 ID
2 receiptNo nvarchar 30 YES 单据编号
3 billingDate datetime (23, 3) YES 开单日期
4 customerID int (10, 0) YES 客户 ID
5 amount char 10 YES 应收/收款金额
6 handlerID int (10, 0) YES 经办人 ID
7 operatorID int (10, 0) YES 操作员 ID
8 remark nvarchar 200 YES 备注
9 type nvarchar 30 YES 类型

B_Sales 商品销售,退货

数据表名称 B_Sales 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 salesID int identity (10, 0) NO PK 销售/退货 ID
2 saleNo nvarchar 30 YES 单号
3 customerID int (10, 0) YES 客户 ID
4 receiptDate datetime (23, 3) YES 收货日期
5 barcode nvarchar 30 YES 条码
6 amountReceivable decimal (8, 2) YES 应收金额
7 paidUpAmount decimal (8, 2) YES 实收金额
8 arrears decimal (8, 2) YES 欠款金额
9 preferentialAmount decimal (8, 2) YES 优惠金额
10 paymentMethodID int (10, 0) YES 付款方式 ID
11 agentID int (10, 0) YES 经办人 ID
12 remark nvarchar 200 YES 备注
13 type nvarchar 20 YES 类型
14 reviewWhether bit 1 YES 审核否
15 reviewerID int (10, 0) YES 审核人 ID
16 auditDate datetime (23, 3) YES 审核日期

B_SalesDetail 商品销售,退货明细

数据表名称 B_SalesDetail 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 salesDetailID int identity (10, 0) NO PK 销售明细 ID
2 salesID int (10, 0) YES 销售 ID
3 productID int (10, 0) YES 商品 ID
4 price decimal (8, 2) YES 售价
5 discount decimal (5, 2) YES 折扣
6 discountPrice decimal (8, 2) YES 折后单价
7 quantity int (10, 0) YES 数量
8 totalAmount decimal (8, 2) YES 总金额
9 remark nvarchar 200 YES 备注

B_SupplierRegistrationBill 供应商:应付,付款登记表

数据表名称 B_SupplierRegistrationBill 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 supplierRegistrationBillID int identity (10, 0) NO PK 应付/付款 ID
2 supplierBillNo nvarchar 30 YES 单据编号
3 billingDate datetime (23, 3) YES 开单日期
4 supplierID int (10, 0) YES 供应商 ID
5 amount decimal (8, 2) YES 应付/付款金额
6 handlerID int (10, 0) YES 经办人 ID
7 operatorID int (10, 0) YES 操作员 ID
8 remark nvarchar 200 YES 备注
9 type nvarchar 30 YES 类型

B_WarehouseChange 仓库:库存调拨,盘点表

数据表名称 B_WarehouseChange 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 warehouseChangeID int (10, 0) NO PK 调拨/盘点 ID
2 oldWarehouseID int (10, 0) YES 调拨前仓库 ID
3 currentWarehouseID int (10, 0) YES 调拨后/当前仓库 ID
4 changeNo nvarchar 30 YES 单号
5 billingDate datetime (23, 3) YES 开单日期
6 inventoryQuantity int (10, 0) YES 库存数量
7 changeNumber int (10, 0) YES 调拨/盘点数量
8 agentID int (10, 0) YES 经手人 ID
9 remark nvarchar 200 YES 备注
10 type nvarchar 30 YES 类型
11 reviewWhether bit 1 YES 审核否
12 reviewerID int (10, 0) YES 审核人 ID
13 auditDate datetime (23, 3) YES 审核日期

B_WarehouseChangeDetail 仓库:库存调拨,盘点明细表

数据表名称 B_WarehouseChangeDetail 数据表描述
SN 字段 数据型态 长度 null PK 描述
1 wChangeDetailID int identity (10, 0) NO PK 调拨/盘点明细 ID
2 warehouseChangeID int (10, 0) YES 调拨 ID
3 productID int (10, 0) YES 商品 ID
4 quantity int (10, 0) YES 调拨/盘点数量
5 inventoryQuantity int (10, 0) YES 库存数量

3、设计与实现
说明:把自己设计的模块分类进行截图展示、该模块用到的数据表和关系描述、界面层经
典代码截图描述。 经典代码定义:界面层控件的特殊使用、数据逻辑的特殊处理,重要
代码截图。
3.1 业务功能 1 名称:进货管理
3.1-1 功能实现
进货管理主要采购进货,退货
(一):采购进货:见图中,是采购进货模块界面
图1
(1)、点击图 中“老商品+”按钮弹出病人资料的界面如图下,
在这里插入图片描述
(2)点击图 中,左边有一列单选框,点击需要添加的商品,选择完之后在点击“加入所选商品”,
商品就会出现在右边的“所选列表中去”。
(3)之后点击图 中 的保存按钮,就会如图 下 所示
在这里插入图片描述
(4)把页面数据填写完整、点击图中“保存”弹出下面:
在这里插入图片描述
(二)待审核采购单:见图 ,是待审核采购单实现界面。
(1)、如图 点击该单号的行列,就会显示出该条账单的商品明细。
在这里插入图片描述
(2)点击“审核否”,进行审核操作
在这里插入图片描述
3.1-2 表和关系
(一)、采购进货:
在这里插入图片描述
(二)待审核采购单:
在这里插入图片描述
3.1-2 经典代码

(1)使用 session 保存数据:

  public ActionResult AddSessionItem(string strProductIDs)
        { 
        ReturnJson msg = new ReturnJson();
        int intSuceessCount = 0;//记录成功数
        int intFailCount = 0;//记录失败数
        //获取添加的商品
        if (!String.IsNullOrEmpty(strProductIDs)){
        
            bool blAdd = true;//记录添加
            //获取session中的进货明细信息表
            List<PurchaseDetailVo> SessionItems = new List<PurchaseDetailVo>();
            if (Session["SessionItem"] != null){
            
                SessionItems = Session["SessionItem"] as List<PurchaseDetailVo>;
            }
            string[] ptudentIDs = strProductIDs.Split(';');
            foreach (string strId in ptudentIDs) {
            
                try
                {
                    //分析
                    //session中商品存在,数量增加
                    //session中商品不存在,添加数据到session
                    //添加商品
                    //获取商品id
                    int intProductID = Convert.ToInt32(strId);
                    //根据名称查询商品基本信息)
 var insertProduct = (from tbProduct in myModal.S_Product join tbUnit in             myModal.S_CommoditiesUnit on tbProduct.commoditiesUnitID equals tbUnit.commoditiesUnitID where tbProduct.productID == intProductID
 select new ProductVo{
                                              productID = tbProduct.productID,//商品id
                                             productName = tbProduct.productName,//名称
                                             commoditiesUnit = tbUnit.commoditiesUnit,
                                             purchasePrice = tbProduct.purchasePrice,
                                               }).ToList();
                                               
                    if (insertProduct.Count() > 0)
                    {
                        //已有的商品中取出
                        //实例化进货明细信息实体
                        PurchaseDetailVo details = new PurchaseDetailVo
                        {
                            productID = insertProduct[0].productID,//商品id
                            productName = insertProduct[0].productName,
                            purchasingPrice = insertProduct[0].purchasePrice,
                            quantity = 1,//数量
                            commoditiesUnit = insertProduct[0].commoditiesUnit,
                            totalAmount = insertProduct[0].purchasePrice * 1,//数量*进价
                            color = insertProduct[0].color,
                            specifications = insertProduct[0].specifications
                        };
                        
                        //判断session中商品存在是否存在
                        for (int i = 0; i < SessionItems.Count; i++)
                        {
                            if (SessionItems[i].productID == intProductID)
                            {
                                blAdd = false;
                                SessionItems[i].quantity = SessionItems[i].quantity + 1;
                                SessionItems[i].totalAmount = (SessionItems[i].quantity + 1) * SessionItems[i].purchasingPrice;
                            }
                        }
                        if (blAdd)
                        {
                            //session中商品不存在,添加数据到session
                            SessionItems.Add(details);
                        }
                        Session["SessionItem"] = SessionItems;//更新session
                        intSuceessCount++;//记录成功条数
                        blAdd = true;//回复默认值
                    }
                    else
                    {
                        msg.Text = "加入所选商品失败!";
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    msg.Text = "数据异常";
                }
            }

            msg.State = true;
            msg.Text = "总共加入" + ptudentIDs.Length + "条商品信息";
            if (intSuceessCount > 0)
            {
                msg.Text += ",成功" + intSuceessCount + "条";
               
            }
            if (intFailCount > 0)
            {
                msg.Text += ",失败" + intFailCount + "条";
            }
        }
        else
        {
            msg.Text = "请选择要加入的商品数据!";
        }
        
        return Json(msg, JsonRequestBehavior.AllowGet);
    }

(2) 自动生成单号数据
//自动生成单据号方法

public string GenerateReceipts(string strQZ,string Number)
{
    try
    {
        string strNumber = "";
        //从第几个开始 截取长度为 几 的字符串
        string date = Number.Substring(0, 8);//日期
        string dtnow = DateTime.Now.ToString("yyyyMMdd");
        //从右边开始取4个字符
        int intNumber = System.Convert.ToInt32(Number.Substring((Number.Trim()).Length - 4));
        //比较单号日期和现在日期
        if (date == dtnow)
        {
            //日期一致;原来单号+1
            strNumber = (intNumber + 1).ToString();
        }
        else
        {
            //日期不一致:从1开始
            strNumber = "1";
        }
        switch (strNumber.Length)
        {
            case 1:
                strNumber = "000" + strNumber;
                break;
            case 2:
                strNumber = "00" + strNumber;
                break;
            case 3:
                strNumber = "0" + strNumber;
                break;
            case 4:
                strNumber = "" + strNumber;
                break;
            default:
                break;
        }
        DateTime dtmNow = DateTime.Now;
        string strYear = dtmNow.Year.ToString().Trim();
        string strMonth = dtmNow.Month.ToString().Trim();
        strMonth = (strMonth.Length == 1 ? "0" + strMonth : strMonth);
        string strDay = dtmNow.Day.ToString().Trim();
        strDay = (strDay.Length == 1 ? "0" + strDay : strDay);
        //简单写法
        //string newdate = DateTime.Now.ToString("yyyyMMdd");
        //string strEndNo = strQZ + newdate + strNumber;
        string strEndNo = strQZ + strYear + strMonth + strDay + strNumber;
        return strEndNo;
    }
    catch (Exception)
    {
        throw;
    }
}

(2)、审核否

<!--自定义列:审核否-->
    <script type="text/html" id="checkboxWheth">
        <!-- 这里的 checked 的状态只是演示 -->
        <input type="checkbox" name="reviewWhether" value="{{d.purchaseID}}" lay-skin="switch" title="审核否" lay-filter="disableDemo" {{ d.reviewWhether == 1 ? 'checked' : '' }}>
    </script>
      //(2)监听审核操作
                form.on('switch(disableDemo)', function (obj) {
                    //layer.tips(this.value + ' ' + this.name + ':' + obj.elem.checked, obj.othis);
                    var ID = this.value;//获取ProductID
                    var bl = obj.elem.checked;//获取值
                    //提示
                    var strText = "";
                    if (bl==true) {
                        strText = "您确定要审核该商品信息";
                    }
                    else {
                        strText = "您确定要取消审核该商品信息";
                    }
                    layer.confirm(strText, { icon: 3, titile: "提示" }, function (index) {
                        $.post("@Url.Content("~/StockManagement/PurchaseStock/DisablePurchase")",
                            {
                                purchaseID: ID,
                                blDisable: bl,
                            },
                            function (returnJson) {
                                if (returnJson.State == true) {
                                    layer.close(index);
                                    //刷新table
                                    PurchaseAsetext();
                                }
                                layer.alert(returnJson.Text, { icon: 6 });
                            });
                    });
                    PurchaseAsetext();
                    
                })

控制器代码

  ··
 public ActionResult DisablePurchase(int purchaseID, bool blDisable)
  
 {
            ReturnJson msg = new ReturnJson();
            try
            {
                //查询要禁用的实体
                B_Purchase dbPurchase = myModal.B_Purchase.Where(o => o.purchaseID == purchaseID).Single();
                dbPurchase.reviewWhether = blDisable;
                //修改
                myModal.Entry(dbPurchase).State = System.Data.Entity.EntityState.Modified;
                if (myModal.SaveChanges() > 0)
                {
                    msg.State = true;
                    if (blDisable == true)
                    {
                        msg.Text = "审核成功!";
                    }
                    else
                    {
                        msg.Text = "取消审核成功!";
                    }
                }
                else
                {
                    msg.Text = "审核失败!";
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                msg.Text = "参数异常!";
            }
            return Json(msg, JsonRequestBehavior.AllowGet)
            }   

3.2 业务功能 2 名称:销售管理
3.2-1 功能实现
销售管理。主要包括商品销售,顾客退货,商品销售查询,部门领用,部门退回,该页面大致与进货略
同。
(一)商品销售查询
在这里插入图片描述
(1)点击表格列,可以看到该条商品的明细信息,所示
在这里插入图片描述
点击 中的”修改可以进行修改该条数据的信息。为采购进货中的修改,该修改与销售的方法一样。
在这里插入图片描述
3.2-2 表和关系
(1)、销售单明细:
在这里插入图片描述
(2)、销售单修改:
在这里插入图片描述
3.2-2 经典代码
(1)下拉框回填数据:
在这里插入图片描述
调用 common 包中的 createSelect 进行下拉框的数据回填
(2)数据库日期控件的回填
在这里插入图片描述
3.4 基础数据功能 4 名称:权限管理

  1. 权限管理主要针对员工登录的页面进行加权管理。
    3.41 功能实现
    (一)权限管理
    权限管理。仅包含角色管理和模块管理
    权限管理给用户登录账号设置模块权限,有的用户不能使用的模块要禁用掉
    (1),首先我们需要给角色设置模块权限,给他加权,角色管理页面点击新增跳到下图页面
    在这里插入图片描述
    该页面可以直接新增角色并给角色添加权限,把该角色需要的功能模块勾选上即可,保存之后一个新的
    角色就可以使用了,新创建一个操作员,添加该角色,就可以访问该角色模块上的数据。
    (2),新增之后页面上有些模块就不能使用了,就会出现无权访问的页面。
    在这里插入图片描述
    (3)修改角色模块
    修改和新增一样,都是保存数据,但是修改是在原有数据上保存数据,点击修改跳出下图页面
    在这里插入图片描述
    该页面既可以修改角色名称,又可以添加权限或去掉权限。
    3.2-2 表和关系
    (1)新增修改权限
    在这里插入图片描述
    3.2-2 经典代码
    (1)模块页面的生成
  </form>
            @*三层 moduleFarID为0的是外层 模块名称*@
            @foreach (S_Module Areaitem in listModules)
            {
                if (Areaitem.moduleFarID == 0)
                {
                    <div class="card mt-3">
                        <div class="card-header">
                            @Areaitem.moduleDescrible
                        </div>
                        <div class="card-body">
                            <div class="row">
                                @*第二层具有功能模块的名称 对应主要是控制器名称*@
                                @foreach (S_Module controllerItem in listModules)
                                {
                                    if (controllerItem.moduleFarID == Areaitem.moduleID)
                                    {
                                        <div class="col-sm-4 col-md-3">
                                            <input type="checkbox" name="@controllerItem.moduleName" value="@controllerItem.moduleID" id="str_@controllerItem.moduleID" />
                                            <label for="str_@controllerItem.moduleID">@controllerItem.moduleDescrible</label>
                                        </div>
                                        @*PNR复制 方法部分*@
                                foreach (S_Module fun in listModules)
                                {
                                    if (fun.moduleFarID == controllerItem.moduleID)
                                    {
                                        <div class="col-sm-4 col-md-3">
                                            <input type="checkbox" name="@fun.moduleName" value="@fun.moduleID" id="str_@fun.moduleID" />
                                            <label for="str_@fun.moduleID">@fun.moduleDescrible</label>
                                        </div>
                                            }

                                        }
                                    }
                                }
                            </div>
                        </div>
                    </div>
                }
            }


            <p class="text-muted text-center my-4">通用进销存系统</p>
            <div class="row">
                <div class="col-12 text-center">
                    <button type="button" class="btn btn-outline-primary mr-2" onclick="InsertPermissionFun()">授 权</button>
                    <button type="button" class="btn btn-outline-secondary ml-2" onclick="btnCancel()">返 回</button>
                </div>
            </div>
        </div>
    </div>

(2)模块新增修改授权

public class ModuleIDEqualityComparer : IEqualityComparer<ModuleID>
    {
        /// <summary>
        /// 确定指定的对象是否相等。
        /// </summary>
        /// <param name="x">第一个类型为 ModuleID 的对象</param>
        /// <param name="y">第二个类型为 ModuleID 的对象</param>
        /// <returns></returns>
        public bool Equals(ModuleID x, ModuleID y)
        {
            return x.moduleID == y.moduleID;
        }
        /// <summary>
        /// 返回指定对象的哈希代码。
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int GetHashCode(ModuleID obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return obj.ToString().GetHashCode();
            }
        }
    }

新增权限

public ActionResult UpdataPermission(S_Role modUserType, List<ModuleID> listModuleID)
    {
        ReturnJson msg = new ReturnJson();
        int addCount = 0;//记录新增成功的数据条数
        int removeCount = 0;//记录移除成功的数据条数
        using (TransactionScope scope = new TransactionScope())
        {
            try
            {
                //获取userTypeID
                int roleID = modUserType.roleID;
                
                //修改角色表 可直接修改
                myModal.Entry(modUserType).State = System.Data.Entity.EntityState.Modified;

                if (myModal.SaveChanges() > 0)
                {
                    //查询出数据库中该用户角色的模块ID 原有的数据
                    List<ModuleID> oldModuleIDs = (from tabPermission in myModal.R_Permission
                                                   where tabPermission.roleID == roleID
                                                   select new ModuleID
                                                   {
                                                       moduleID = tabPermission.moduleID,
                                                   }).ToList();

                    //这里面应该有3中情况:
                    //①需要新增的(数据库里面没有的) listModuleID中有,而oldModuleIDs中没有的
                    //②需要删除的 listModuleID中没有,oldModuleIDs中有的
                    //③保持不变的 listModuleID中有的,oldModuleIDs中也有的

                    //1,先查找保持不变的 listModuleID 和 oldModuleIDs的交集
                    List<ModuleID> existList = listModuleID.Intersect(oldModuleIDs, new ModuleIDEqualityComparer()).ToList();
                    //2,新增的 取差集
                    List<ModuleID> addList = listModuleID.Except(existList, new ModuleIDEqualityComparer()).ToList();
                    //3,删除的 取差集
                    List<ModuleID> removeList = oldModuleIDs.Except(existList, new ModuleIDEqualityComparer()).ToList();
                    //先删除removeList 中的数据
                    if (removeList.Count > 0)
                    {
                        //获取需要删除的moduleID
                        List<int> removeIDs = removeList.Select(o => o.moduleID).ToList();
                        //查询出需要删除的 权限信息
                        List<R_Permission> removePermissions = myModal.R_Permission.Where(o => removeIDs.Contains(o.moduleID) && o.roleID == roleID).ToList();
                        //删除数据
                        myModal.R_Permission.RemoveRange(removePermissions);
                        //更新到数据库 记录被删除的行
                        removeCount = myModal.SaveChanges();
                    }

                    //新增数据
                    if (addList.Count > 0)
                    {
                        //存放要新增到权限表
                        List<R_Permission> addPermissions = new List<R_Permission>();
                        //遍历addList 创建需要保存的数据
                        foreach (ModuleID item in addList)
                        {
                            R_Permission modPer = new R_Permission
                            {
                                moduleID = item.moduleID,
                                roleID = roleID,
                                isEnable = true
                            };
                            addPermissions.Add(modPer);
                        }
                        //新增到数据库 并记录 新增行数
                        myModal.R_Permission.AddRange(addPermissions);
                        addCount = myModal.SaveChanges();
                    }
                    if ((removeList.Count + addList.Count) == (removeCount + addCount))
                    {
                        //提交事务
                        scope.Complete();
                        msg.State = true;
                        msg.Text = "授权成功!";

                    }
                    else
                    {
                        msg.Text = "授权失败!";
                    }
                }
                else
                {
                    msg.Text = "授权失败!";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                msg.Text = "数据异常授权失败!";
            }
        }

        return Json(msg, JsonRequestBehavior.AllowGet);
    }

(3)App_Start文件夹给权限设置过滤器

namespace WebApplication
{
    public class FilterConfig
    {
        /// <summary>
        /// 注册全局的过滤器
        /// </summary>
        /// <param name="filters"></param>
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //全局默认的过滤器 错误处理
            filters.Add(new HandleErrorAttribute());

            //添加自定义的权限过滤器
            filters.Add(new PermissionFilter());
        }
    }
}   

(4)登录时筛选检查 url

  public class PermissionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            int loginUserID = 0;
            try
            {
                //获取请求的URL路径
                string url = filterContext.HttpContext.Request.Url.AbsolutePath;
                //检查是否登录
                //跳过登录检查的URL
                if (url == "/" || url == "/Main/Login" || url == "/Main/CreateValidCode" || url == "/Main/UserLogin")
                {
                    return;
                }
                loginUserID = Convert.ToInt32(filterContext.HttpContext.Session["UserID"].ToString());

                //权限检查 默认页面不检查 主控制器不检查
                if (url == "/" || url.Contains("/Main/"))
                {
                    return;
                }
                //1,获取在登录时,查询的权限模块信息
                List<ModuleVo> userModules = filterContext.HttpContext.Session["userModules"] as List<ModuleVo>;


                string[] strUrls = url.Split('/');//根据/分割 -> 0-空字符串,1-区域名称,2-控制器名称,3-Action
                if (strUrls.Length >= 4)
                {
                    string areaName = strUrls[1];//获取区域名称
                    string controllerName = strUrls[2];//获取控制器名称
                    //一般情况下 判断 区域和控制器
                    int exist = userModules.Count(o => o.moduleName == controllerName && o.parentModule.moduleName == areaName);
                    if (exist == 0)
                    {
                        filterContext.HttpContext.Response.Redirect("/Main/NoPermission");
                    }

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                filterContext.HttpContext.Response.Redirect("/Main/Login");

            }
        }
    }

没了!!!!!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值