Asp.Net生成无限级菜单

首先创建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();
        }

    }
}
时间: 2024-10-06 16:09:45

Asp.Net生成无限级菜单的相关文章

生成树形菜单

题记------学习别人的精髓,并加以总结,消化吸收,这就是提高!!! 动态生成树形菜单,前台用easyui实现,非常简单不赘述,主要给出后台java的逻辑代码 1 package com.gongli.util.entity.treeMenu; 2 3 4 5 /* 6 * 用于封装树形菜单,无具体表与之对应,根节点为-1,节点0,然后父节点0,节点001,父节点001,节点001001,001002,001...依次类推 7 */ 8 public class TreeMenu { 9 pr

动态生成多级菜单

MVC5+EF6 入门完整教程13 -- 动态生成多级菜单 稍微有一定复杂性的系统,多级菜单都是一个必备组件. 本篇专题讲述如何生成动态多级菜单的通用做法. 我们不用任何第三方的组件,完全自己构建灵活通用的多级菜单. 需要达成的效果:容易复用,可以根据model动态产生. 文章提纲 概述要点 && 理论基础 详细步骤 一.分析多级目录的html结构 二.根据html结构构建data model 三.根据data model动态生成树形结构 四.解析树形结构成html 总结 概述要点 &am

Asp.Net 生成网站时不生成.pdb文件

Asp.Net默认情况下生成网站发布时,打开Bin文件夹,每个类库会对应生成一个类库名.pdb文件... .pdb是用来放置VS的调试信息的,项目发布后可以删除它. 右键点击类库项目,在属性里.生成,点高级,调试信息默认是 full ,你可以选择成 none,就是不调试.保存就可以了. 原文转载 http://www.dyxue.com/tech/id2547.html Asp.Net 生成网站时不生成.pdb文件,布布扣,bubuko.com

用C#从数据库动态生成AdminLTE菜单的一种方法

用C#从数据库动态生成AdminLTE菜单的一种方法 当前的应用设计风格趋于Flat扁平化,很多基于BootStrap实现了很多UI非常漂亮的管理界面(Bootstrap admin template). 此核心文件开源在Github:https://github.com/JackWangCUMT/AdminLTE-Menu-Generate.首先看一下主界面: 查看左边导航的菜单html结构(下面代码有错误,HTML自定义属性直接用空格进行分割,而不是,号进行分割,不然jquery获取定义属性

asp.net 生成PDF方法

今天转博客园看到有人发表了一篇生成PFd的文章,准备自己也留一份准备以后用到的时候方便调用: 首先去itextsharp网站下载控件(https://sourceforge.net/projects/itextsharp) 将下载后的控件引用到自己的项目里面,主要的bll文件为:itextsharp.dll文件 1.根据DataTable生成PDF文件 添加Itextsharp引用 using iTextSharp;using iTextSharp.text;using iTextSharp.t

ASP.NET生成WORD文档,服务器部署注意事项

网上转的,留查备用,我服务器装的office2007所以修改的是Microsoft Office word97 - 2003 文档这一个. ASP.NET生成WORD文档服务器部署注意事项 1.Asp.net 2.0在配置Microsoft Excel.Microsoft Word应用程序权限时 error: 80070005 和8000401a 的解决总   2007-11-01 11:30  检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-00000

Asp.net 生成静态页面

第一次发表,有什么错误,请大家谅解噢! 如果不明白的话,建议自己拷一次. 就会的了.. 开发步骤: 1.路径映射类(UrlMapping),主要对路径进行拆分.拼接.(关键的一步) 2.过滤流类(FilterStream),主要负责生成静态页面. 3.静态页面类(HtmlPage),主要是调用UrlMapping和FilterStream类, 哪个页面想静态化,就继承这个类. 4.HtmlHandler类,路径后缀为Html的,都由它来处理,与HtmlPage类相似. 5.HtmlPanel类(

asp.net生成HTML静态页

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.T

WPF后台动态生成右键菜单

#region 循环生成右键菜单 private ContextMenu ContextMenus(Dictionary<string, RoutedEventHandler> list) { ContextMenu cm = new ContextMenu(); Style style = (Style)this.FindResource("ContextMenu"); //定义前台显示模板 cm.Style = style; foreach (var dc in lis