• 【EasyUI】权限管理(二)显示左侧菜单


    效果图:

     Login.aspx页面代码:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="EasyUIWeb.Login" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link href="Script/jquery-easyui-1.7.0/themes/default/easyui.css" rel="stylesheet" />
        <link href="css/wu.css" rel="stylesheet" />
        <link href="css/icon.css" rel="stylesheet" />
        <script src="Script/jquery-easyui-1.7.0/jquery.min.js"></script>
        <script src="Script/jquery-easyui-1.7.0/jquery.easyui.min.js"></script>
        <script src="Script/jquery-easyui-1.7.0/locale/easyui-lang-zh_CN.js"></script>
        <script src="Script/Public/valid-zh.js"></script>
        <script src="Script/Public/Common.js"></script>
    
        <script type="text/javascript">
            var login = function () {
                var loginName = $('#Text_loginName').val();
                var loginPwd = $('#Text_loginPwd').val();
                
                $("#ff").form('submit', {
                    url: '/Handlers/LoginHandler.ashx?action=Login&loginName=' + encodeURI(loginName) + '&loginPwd=' + encodeURI(loginPwd),
                    onSubmit: function () {
                        return $(this).form('validate'); 
                    },
                    success: function (result) {
                        result = eval('(' + result + ')');
                        if (result.Success) {
                            if (result.Message > 0) {
                     document.cookie = "userID=" + result.Message //sessionStorage.setItem(
    "userID", result.Message) sessionStorage.setItem("userName", loginName) window.location.href = "Home.aspx"; } $('#dd').dialog('close'); } else { $.messager.show({ title: '错误', msg: result.Message }); } } }) } </script> </head> <body> <div id="dd" class="easyui-window" data-options="iconCls:'icon-user-b',buttons:'#dlg-buttons',modal:true,350,height:250" title="用户登录"> <form id="ff" method="post" autocomplete="off" style="margin-top: 30px" action="Home.aspx"> <table class="tb1"> <tr> <td class="td1">用户名:</td> <td class="td2"> <input type="text" id="Text_loginName" name="loginName" class="easyui-validatebox textbox" data-options="prompt:'UserName',required:true,validType:'length[2,20]'" style=" 170px; height: 22px;" /> </td> </tr> <tr> <td class="td1">&nbsp;码:</td> <td class="td2"> <input type="password" id="Text_loginPwd" name="loginPwd" class="easyui-validatebox textbox" style=" 170px; height: 22px;" data-options="prompt:'Password',required:true" /> </td> </tr> </table> <div id="dlg-buttons" style="margin-left: 200px; margin-top: 30px"> <a id="ddok" href="javascript:void(0)" onclick="javascript:login();" class="easyui-linkbutton" data-options="iconCls:'icon icon-ok'">登录</a> <a id="ddcancel" href="javascript:void(0)" onclick="javascript:$('#dd').window('close');" class="easyui-linkbutton" data-options="iconCls:'icon icon-cancel'">取消</a> </div> </form> </div> </body> </html>

    Home.aspx页面代码:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="EasyUIWeb.Home" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link href="Script/jquery-easyui-1.7.0/themes/default/easyui.css" rel="stylesheet" />
        <link href="css/wu.css" rel="stylesheet" />
        <link href="css/icon.css" rel="stylesheet" />
        <script src="Script/jquery-easyui-1.7.0/jquery.min.js"></script>
        <script src="Script/jquery-easyui-1.7.0/jquery.easyui.min.js"></script>
        <script src="Script/jquery-easyui-1.7.0/locale/easyui-lang-zh_CN.js"></script>
        <script src="Script/Public/Main.js"></script>
        <script src="Script/Menu.js"></script>
         
    </head>
    <body class="easyui-layout">
        <div class="wu-header" data-options="region:'north',border:false,split:true">
            <div class="wu-header-left">
                <h1>EasyUI Web Admin</h1>
            </div>
            <div class="wu-header-right">
                <p><span  id="span_userName" style="color: red "><strong class="easyui-tooltip" title="2条未读消息" >admin</strong></span>,欢迎您!</p>
            </div>
        </div>
        <div class="wu-sidebar" data-options="region:'west',split:true,border:true,title:'导航菜单'">
            <div class="easyui-accordion" data-options="border:false,fit:true" id="RightAccordion"> 
            </div>
        </div>
    
        <div class="wu-main" data-options="region:'center'">
            <div id="wu-tabs" class="easyui-tabs" data-options="border:false,fit:true"> 
            </div>
        </div>
    
        
    
        <div class="wu-footer" data-options="region:'south',border:true,split:true">
            &copy; 2019 All Rights Reserved
        </div>
    </body>
    </html>

    Menu.JS代码:

    $(function () {
        var userName = sessionStorage.getItem("userName");
    
        //if (userName == null || userName == "") {
        //    window.top.location.href = "Login.aspx";
        //}
    
        window.document.getElementById("span_userName").innerText = userName
    
        $("#RightAccordion").accordion({ //初始化accordion
            fillSpace: true,
            fit: true,
            border: false,
            animate: false
        });
    
        var userId = getCookie("userID")
        $.ajax({
            type: 'post',
            dataType: "json",
            url: "/Handlers/MenuHandler.ashx?action=LoadMenu&userId=" + userId + "&menuParId='1'",
            success: function (data) {
                $.each(data, function (i, n) {
                    var menuId = n.id;
    
                    $('#RightAccordion').accordion('add', {
                        title: n.text,
                        selected: true,
                        iconCls: n.iconCls,
                        content: "<ul id='tree" + menuId + "' ></ul>"
                    });
                    $.parser.parse();
                    $.getJSON(
                        "/Handlers/MenuHandler.ashx?action=LoadMenu&userId=" + userId + "&menuParId='" + menuId + "' ",
                        null,
                        function (result) {
                            $("#tree" + menuId).tree({
                                data: result,
                                onBeforeExpand: function (node, param) {
                                    $("#tree" + menuId).tree('options').url = "/Handlers/MenuHandler.ashx?action=LoadMenu&userId=" + userId + "&menuParId=' " + node.menuId + "' ";
                                },
                                onClick: function (node) {
                                    var tabTitle = node.text;
                                    var url = node.menuUrl;
                                    var icon = node.iconCls;
                                    addTab(tabTitle, url, icon);
                                }
                            });
                        }
    
                    );
                })
            }
        })
    })
    
    function getCookie(name) {
        let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null) return unescape(arr[2]);
        return null;
    }
    
    //选项卡
    function addTab(title, url, icon) {
        if ($('#wu-tabs').tabs('exists', title)) {
            $('#wu-tabs').tabs('select', title);
        } else {
            var content = '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="100%;height:100%;"></iframe>';
            $('#wu-tabs').tabs('add', {
                title: title,
                content: content,
                iconCls: icon,
                closable: true
            });
        }
    }

    LoginHandler.ashx、DAL和BLL代码:

    using System;
    using System.Collections.Generic;
    using System.Web;
    using BLL;
    using Common.Web;
    using Model;
    
    namespace EasyUIWeb.Handlers
    {
        /// <summary>
        /// LoginHandler 的摘要说明
        /// </summary>
        public class LoginHandler : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                var action = Request.GetQueryString("Action");
                try
                {
                    switch (action)
                    {
                        case "Login":
                            this.CheckUserLogin(context);
                            break;
    
                        default:
    
                            break;
                    };
                }
                catch (Exception ex)
                {
                    Response.OutResult(context, new MsgResult() { Success = false, Message = ex.ToString() });
                }
            }
    
            public void CheckUserLogin(HttpContext context)
            {
                string sMsg = string.Empty;
                string loginName = Request.GetFormString("loginName");
                string loginPwd = Request.GetQueryString("loginPwd");
    
                List<Model_tb_users> userList = new BLL_Login().CheckUserLogin(loginName, loginPwd);
    
                int userID = 0;
                if (userList != null && userList.Count > 0)
                {
                    foreach (var item in userList)
                    {
                        if (item.diasble)
                        {
                            sMsg = "用户已被禁用,请您联系管理员!";
                        }
                        userID = item.userId;
                    } 
                }
                else
                {
                    sMsg = "用户名密码错误,请您检查!";
                }
    
                if (string.IsNullOrWhiteSpace(sMsg))
                {
                    Response.OutResult(context, new MsgResult() { Success = true, Message = userID.ToString() });
                }
                else
                {
                    Response.OutResult(context, new MsgResult() { Success = false, Message = sMsg });
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    
    
    
    
    
    
    
    
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Text;
    using Common;
    using DAL;
    using Model;
    
    namespace BLL
    {
        public class BLL_Login
        {
            private readonly DAL_Login dal = new DAL_Login();
            /// <summary>
            /// 根据用户id查询有相关权限的菜单
            /// </summary>
            /// <param name="userId"></param>
            /// <returns></returns>
            public List<Model_tb_users> CheckUserLogin(string loginName, string loginPwd)
            {
                DataSet ds = this.dal.CheckUserLogin(loginName, loginPwd);
                return ModelHandler<Model_tb_users>.FillModel(ds.Tables[0]);
            }
        }
    }
    
    
    
    
    
    
    
    using System.Data;
    using System.Data.SqlClient;
    using System.Text;
    using DBUtility;
    
    namespace DAL
    {
        public class DAL_Login
        {
            public DataSet CheckUserLogin(string loginName, string loginPwd)
            {
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append("SELECT * FROM dbo.tb_users  ");
                sbSql.Append(" WHERE userName=@loginName AND userPassWord=@loginPwd ");
    
                SqlParameter[] paras =
                {
                    new SqlParameter("@loginName",loginName),
                    new SqlParameter("@loginPwd",loginPwd)
                };
    
                return DbHelperSQL.Query(sbSql.ToString(), paras);
            }
        }
    }
    View Code

    MenuHandler.ashx、DAL和BLL代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Common.Web;
    using Model;
    using BLL;
    using Newtonsoft.Json;
    
    namespace EasyUIWeb.Handlers
    {
        /// <summary>
        /// MenuHandler 的摘要说明
        /// </summary> 
        public class MenuHandler : IHttpHandler
        { 
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                var action = Request.GetQueryString("Action");
                try
                {
                    switch (action)
                    {
                        case "LoadMenu":
                            this.LoadMenu(context);
                            break;
                       
                        default:
    
                            break;
                    };
                }
                catch (Exception ex)
                {
                    Response.OutResult(context, new MsgResult() { Success = false, Message = ex.ToString() });
                }
            }
    
            public void LoadMenu(HttpContext context)
            {
                int userId = Request.GetQueryInt("userId",0);
                string menuParId = Request.GetQueryString("menuParId");
    
                List<Model_Navigation> menuList = new BLL_Menu().GetUserMenuData(userId, menuParId);
    
                string jsonStr = JsonConvert.SerializeObject(menuList);
    
                Response.WriteJson(context, jsonStr);
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    
    
    
    
    
    
    using System.Data;
    using DBUtility;
    
    namespace DAL
    {
        public class DAL_Menu
        {
            /// <summary>
            /// 根据用户id查询有相关权限的菜单
            /// </summary>
            /// <param name="userId"></param>
            /// <returns></returns>
            public DataSet GetUserMenuData(int userId, string menuParId)
            {
                string sql = @"SELECT distinct(m.menuName) as text, m.menuId as id, m.menuIcon as iconCls, m.menuParId, m.menuUrl  FROM tb_users users
    INNER JOIN  dbo.tb_users_role ur  ON users.userId = ur.userId
    INNER JOIN dbo.tb_role_menu_button rmb ON ur.roleId = rmb.roleId
    INNER JOIN dbo.tb_menu m ON rmb.menuId = m.menuId
    WHERE users.userId = " + userId + " AND m.menuParId = " + menuParId + " order by m.menuParId";
    
                return DbHelperSQL.Query(sql);
            }
        }
    }
    
    
    
    
    
    
    using System.Collections.Generic;
    using System.Data;
    using Common;
    using DAL;
    using Model;
    
    namespace BLL
    {
        public class BLL_Menu
        {
            private readonly DAL_Menu dal = new DAL_Menu();
            /// <summary>
            /// 根据用户id查询有相关权限的菜单
            /// </summary>
            /// <param name="userId"></param>
            /// <returns></returns>
            public List<Model_Navigation> GetUserMenuData(int userId, string menuParId)
            {
                DataSet ds = this.dal.GetUserMenuData(userId, menuParId);
                return ModelHandler<Model_Navigation>.FillModel(ds.Tables[0]);
            }
        }
    }
    View Code

     Model:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Model
    {
        /// <summary>
        /// Model_tb_button:实体类(属性说明自动提取数据库字段的描述信息)
        /// </summary>
        [Serializable]
        public partial class Model_tb_button
        {
            public Model_tb_button()
            { }
            #region Model
            private int _btnid;
            private string _btnname;
            private string _btncode;
            private string _btnicon;
            private DateTime? _createtime = DateTime.Now;
            private string _createby;
            private DateTime? _updatetime = DateTime.Now;
            private string _updateby; 
            /// <summary>
            /// 
            /// </summary>
            public int btnId
            {
                set { _btnid = value; }
                get { return _btnid; }
            }
            /// <summary>
            /// 
            /// </summary>
            public string btnName
            {
                set { _btnname = value; }
                get { return _btnname; }
            }
            /// <summary>
            /// 
            /// </summary>
            public string btnCode
            {
                set { _btncode = value; }
                get { return _btncode; }
            }
            /// <summary>
            /// 
            /// </summary>
            public string btnIcon
            {
                set { _btnicon = value; }
                get { return _btnicon; }
            }
            /// <summary>
            /// 
            /// </summary>
            public DateTime? createTime
            {
                set { _createtime = value; }
                get { return _createtime; }
            }
            /// <summary>
            /// 
            /// </summary>
            public string createBy
            {
                set { _createby = value; }
                get { return _createby; }
            }
            /// <summary>
            /// 
            /// </summary>
            public DateTime? updateTime
            {
                set { _updatetime = value; }
                get { return _updatetime; }
            }
            /// <summary>
            /// 
            /// </summary>
            public string updateBy
            {
                set { _updateby = value; }
                get { return _updateby; }
            } 
            #endregion Model
    
        }
    }
    
    
    
    
    
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Model
    {
        [Serializable]
        public partial class Model_Navigation
        {
            //public string menuId { get; set; }
            //public string menuname { get; set; }
            public string id { get; set; }
            public string text { get; set; }
            //public string menuIcon { get; set; }
            public string iconCls { get; set; }
            public string menuParId { get; set; }
            public string menuUrl { get; set; }
        }
    }
    View Code

    验证是否登录基类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.SessionState;
    
    namespace EasyUIWeb.App_Start
    {
        public class CheckLoginPageBase : System.Web.UI.Page
        {
            protected virtual void Page_Load(object sender, EventArgs e)
            {
                //这里进行判断
                if (Request.Cookies["userID"] == null)
                {
                    Response.Redirect("~/Login.aspx");
                }
            } 
    
        }
    }
    
    
    
    
    
    
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using EasyUIWeb.App_Start;
    
    namespace EasyUIWeb
    {
        public partial class Home : CheckLoginPageBase
        {
            protected override void Page_Load(object sender, EventArgs e)
            {
                base.Page_Load(sender, e);
            }
        }
    }
    View Code
  • 相关阅读:
    sql学习笔记
    正则表达式30分钟入门教程(转) 收藏
    学习Javascript闭包(Closure)
    Bug等级规范
    下载1G的东西用1M网速理论上要用多长时间?
    C#多线程学习(四) 多线程的自动管理(线程池)
    JS调用WebServers
    北京软件公司排名
    Js调用WebServices
    C#多线程学习(三) 生产者和消费者
  • 原文地址:https://www.cnblogs.com/zhaoyl9/p/11104117.html
Copyright © 2020-2023  润新知