Asp.Net生成无限级菜单

http://www.cnblogs.com/yeminglong/p/4490332.html

首先创建SQL脚本

复制代码
if exists (select * from sysobjects where id = OBJECT_ID('[Menu]') and OBJECTPROPERTY(id, 'IsUserTable') = 1) 
DROP TABLE [Menu]

CREATE TABLE [Menu] (
[ID] [bigint]  IDENTITY (1, 1)  NOT NULL,
[MenuName] [nvarchar]  (200) NULL,
[Menu_ICON] [bigint]  NOT NULL DEFAULT (0),
[Menu_URL] [varchar]  (500) NULL,
[ParentID] [bigint]  NOT NULL DEFAULT (0),
[AddTime] [datetime]  NOT NULL,
[ICON_URL] [varchar]  (500) NULL)

ALTER TABLE [Menu] WITH NOCHECK ADD  CONSTRAINT [PK_sys_menu] PRIMARY KEY  NONCLUSTERED ( [ID] )
SET IDENTITY_INSERT [Menu] ON
复制代码

页面代码

复制代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="common_menu.aspx.cs" Inherits="AccordMenu.common_menu" %>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <style type="text/css">
        body
        {
            margin: 0;
            padding: 30px;
            background: #FFF;
            color: #666;
        }
        h1
        {
            font: bold 16px Arial, Helvetica, sans-serif;
        }
        p
        {
            font: 11px Arial, Helvetica, sans-serif;
        }
        a
        {
            color: #900;
            text-decoration: none;
        }
        a:hover
        {
            background: #900;
            color: #FFF;
        }
        /*CSS Code for Menu Begin:*/
        /* Root = Vertical, Secondary = Vertical */
        ul#navmenu, ul#navmenu li, ul#navmenu ul
        {
            margin: 0;
            border: 0 none;
            padding: 0;
            width: 160px; /*For KHTML*/
            list-style: none;
        }
        ul#navmenu li
        {
            display: block !important; /*For GOOD browsers*/
            display: inline; /*For IE*/
            position: relative;
        }
        /* Root Menu */
        ul#navmenu a
        {
            border: 1px solid #FFF;
            border-right-color: #CCC;
            border-bottom-color: #CCC;
            padding: 0 6px;
            display: block;
            background: #EEE;
            color: #666;
            font: bold 10px/22px Verdana, Arial, Helvetica, sans-serif;
            text-decoration: none;
            height: auto !important;
            height: 1%; /*For IE*/
        }
        /* Root Menu Hover Persistence */
        ul#navmenu a:hover, ul#navmenu li:hover a, ul#navmenu li.iehover a
        {
            background: #CCC;
            color: #FFF;
        }
        /* 2nd Menu */
        ul#navmenu li:hover li a, ul#navmenu li.iehover li a
        {
            background: #EEE;
            color: #666;
        }
        /* 2nd Menu Hover Persistence */
        ul#navmenu li:hover li a:hover, ul#navmenu li:hover li:hover a, ul#navmenu li.iehover li a:hover, ul#navmenu li.iehover li.iehover a
        {
            background: #CCC;
            color: #FFF;
        }
        /* 3rd Menu */
        ul#navmenu li:hover li:hover li a, ul#navmenu li.iehover li.iehover li a
        {
            background: #EEE;
            color: #666;
        }
        /* 3rd Menu Hover Persistence */
        ul#navmenu li:hover li:hover li a:hover, ul#navmenu li:hover li:hover li:hover a, ul#navmenu li.iehover li.iehover li a:hover, ul#navmenu li.iehover li.iehover li.iehover a
        {
            background: #CCC;
            color: #FFF;
        }
        /* 4th Menu */
        ul#navmenu li:hover li:hover li:hover li a, ul#navmenu li.iehover li.iehover li.iehover li a
        {
            background: #EEE;
            color: #666;
        }
        /* 4th Menu Hover */
        ul#navmenu li:hover li:hover li:hover li a:hover, ul#navmenu li.iehover li.iehover li.iehover li a:hover
        {
            background: #CCC;
            color: #FFF;
        }
        ul#navmenu ul, ul#navmenu ul ul, ul#navmenu ul ul ul
        {
            display: none;
            position: absolute;
            top: 0;
            left: 160px;
        }
        /* Do Not Move - Must Come Before display:block for Gecko */
        ul#navmenu li:hover ul ul, ul#navmenu li:hover ul ul ul, ul#navmenu li.iehover ul ul, ul#navmenu li.iehover ul ul ul
        {
            display: none;
        }
        ul#navmenu li:hover ul, ul#navmenu ul li:hover ul, ul#navmenu ul ul li:hover ul, ul#navmenu li.iehover ul, ul#navmenu ul li.iehover ul, ul#navmenu ul ul li.iehover ul
        {
            display: block;
        }
    </style>
    <script type="text/javascript">
        <!--
        navHover = function () {
            var lis = document.getElementById("navmenu").getElementsByTagName("LI");
            for (var i = 0; i < lis.length; i++) {
                lis[i].onmouseover = function () {
                    this.className += " iehover";
                }
                lis[i].onmouseout = function () {
                    this.className = this.className.replace(new RegExp(" iehover\\b"), "");
                }
            }
        }
        if (window.attachEvent) window.attachEvent("onload", navHover);

        function gotoURL(szURL) {
            if (szURL == "") return;
            window.open(szURL, 'Main', '');
        }

        function SelectMenu(object, szURL) {
            for (var i = 0; i < document.all.length; i++) {
                if (document.all(i).className == "SelectedMenuLevel2")
                    document.all(i).className = "MenuLevel2"
                else if (document.all(i).className == "SelectedMenuLevel1")
                    document.all(i).className = "MenuLevel1"
            }
            if (object.className == "MenuLevel2")
                object.className = "SelectedMenuLevel2";
            else if (object.className == "MenuLevel1")
                object.className = "SelectedMenuLevel1";
            gotoURL(szURL);
        }
        function resizeMenu() {
            if (Menu.style.display == '') {
                Menu.style.display = 'none';
                resizeIcon_Show.style.display = 'none';
                resizeIcon_Hidden.style.display = '';
                top.Bottom.cols = '7,*';
            }
            else {
                Menu.style.display = '';
                resizeIcon_Show.style.display = '';
                resizeIcon_Hidden.style.display = 'none';
                top.Bottom.cols = '180,*';
            }
        }
        -->
    </script>
</head>
<body>
    <table height="100%" cellspacing="0" cellpadding="0" border="0">
        <tr valign="top">
            <td id="Menu" style="width: 180">
                <!--**-->
                <table height="100%" width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr valign="top">
                        <td valign="middle" align="center" background="../images/Desk/ResizeBg.gif" style="width: 7px">
                            &nbsp;
                        </td>
                        <td>
                            <ul id="navmenu">
                                <%= _menu %>
                            </ul>
                        </td>
                    </tr>
                </table>
            </td>
            <td valign="middle" align="center" background="../images/Desk/ResizeBg.gif" style="width: 7px">
                <span id="resizeIcon_Show" style="cursor: hand" onclick="javascript:resizeMenu()"
                    title="隐藏菜单">
                    <img src="../images/Desk/Resize_Hidden.gif" width="7" height="48"></span> <span id="resizeIcon_Hidden"
                        style="display: none; cursor: hand" onclick="javascript:resizeMenu()" title="显示菜单">
                        <img src="../images/Desk/Resize_Show.gif" width="7" height="48"></span>
            </td>
        </tr>
    </table>
    <script language="javascript" event="oncontextmenu" for="document">
              if (!event.ctrlKey) return false;
    </script>
</body>
</html>
复制代码

后台代码

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;

namespace AccordMenu
{

    public partial class common_menu : System.Web.UI.Page
    {
        protected void Page_Load(object sender, System.EventArgs e)
        {
            //try
            //{
            //    string CheckSessionStr = Session["id"].ToString();
            //}
            //catch
            //{
            //    Response.Write("<script language=javascript>alert('请登录');top.location='../index.aspx'</script>");
            //}

            if (!IsPostBack)
            {
                ListMenu();
            }
        }

        protected string _menu = string.Empty;
        public void ListMenu()
        {
            StringBuilder sb = new StringBuilder();
            DataTable _list = new DataTable();
            string ConctionStr = "Data Source=127.0.0.1;Initial Catalog=AccordMenu;Integrated Security=False;User ID=sa;Password=sa";
            using (SqlConnection conec = new SqlConnection(ConctionStr))
            {
                conec.Open();
                string SqlText = "SELECT * FROM sys_menu";
                SqlCommand Comand = new SqlCommand(SqlText, conec);
                SqlDataAdapter Adaper = new SqlDataAdapter(Comand);
                Adaper.Fill(_list);
                Adaper.Dispose();
                Comand.Dispose();
                conec.Close();
            }
            DataRow[] rows = _list.Select("ParentID=0");
            foreach (DataRow dr in rows)
            {
                string id = dr["ID"].ToString();
                string name = dr["MenuName"].ToString();
                sb.AppendFormat("<li ID=\"{2}\"><a href=\"javascript:;\" onclick=\"gotoURL('{0}');\">{1}</a>\r\n", dr["Menu_URL"].ToString(), name, id);//href可以写需要的链接地址
                sb.Append(GetSubMenu(id, _list));
                sb.Append("</li>\r\n");
            }
            _menu = sb.ToString();

        }

        /// <summary>
        /// 递归调用生成无限级别
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private string GetSubMenu(string pid, DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            DataRow[] rows = dt.Select("ParentID=" + pid);
            sb.Append("<ul>\r\n");
            foreach (DataRow dr in rows)
            {
                string id = dr["ID"].ToString();
                string name = dr["MenuName"].ToString();
                sb.AppendFormat("<li ID=\"{2}\"><a href=\"javascript:;\" onclick=\"gotoURL('{0}');\">{1}</a>\r\n", dr["Menu_URL"].ToString(), name, id);//href可以写需要的链接地址
                sb.Append(GetSubMenu(id, dt));  //递归
                sb.Append("</li>\r\n");
            }
            sb.Append("</ul>\r\n");
            return sb.ToString();
        }

    }
}
复制代码

 

posted @ 2017-02-10 15:26  清空回声  阅读(261)  评论(0编辑  收藏  举报