Montar um menu, por menor que seja, dá muito trabalho para qualquer desenvolvedor. Hoje em dia é exigido do programador que além de conhecer a parte de desenvolvimento também conheça um pouco sobre designer, para que os aplicativos web criados por ele fiquem com uma cara um pouco mais amigável, no entanto, hoje se pode encontrar muitos templates prontos na web, todos em CSS e JavaScript. Porém, esses layout geralmente são feitos estaticamente. Por isso, nesse artigo vamos criar um menu dinâmico e atrativo de forma bem rápida. E esse poderá ser utilizado em qualquer projeto

Vendo esse cenário, vamos mostrar hoje como criar um menu dinâmico utilizando ASP.NET, CSS e JavaScript, assim você poderá utilizar esse exemplo para qualquer CSS que encontrar e ter um menu mais atrativo e com o diferencial de ser totalmente dinâmico.

Para quem não conhece muito e deseja aprender mais sobre a linguagem da Microsoft, não deixe de dar uma conferida nesse curso de ASP.NET

Vamos iniciar pela criação da tabela no banco de dados, então abram o Management Studio e conecte em uma instância no bd. Feito isso, localize sua Base de Dados e clique com o botão direito do mouse e selecione a opção new query, conforme a Figura 1, e coloque o código da Listagem 1.

Figura 1. Acessando uma nova Query.

Listagem 1. Código de criação da Tabela.


  CREATE TABLE [dbo].[MENU](
        [ID_MENU] [int] IDENTITY(1,1) NOT NULL,
        [DESCR_MENU] [varchar](50) NOT NULL,
        [NOME_MENU] [varchar](50) NOT NULL,
        [HIERARQUIA_MENU] [varchar](150) NULL,
   CONSTRAINT [PK_MENU] PRIMARY KEY CLUSTERED 
  (
        [ID_MENU] ASC
  )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]
   
  GO

Após a tabela criada, é necessário alimentá-la. Caso queira, segue na Listagem 2 o código, mas se preferir pode preenche-la da forma que achar necessário.

Listagem 2. Inserindo Registros na Tabela.


  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('HOME','HOME',null,'HOME.aspx')
  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('ARQUIVO','ARQUIVO',null,null)
  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('NOVO','NOVO','ARQUIVO',null)
  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('PROJETO','PROJETO','NOVO','Projeto.aspx')
  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('SOLUÇÃO','SOLUCAO','NOVO','Solucao.aspx')
  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('CONFIGURAR','CONFIGURAR',null,null)
  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('PROJETO','PROJETO','CONFIGURAR','CONFIGPROJETO.aspx')
  Insert Into Menu (DESCR_MENU,NOME_MENU,HIERARQUIA_MENU,LINK_MENU) values('SOLUÇÃO','SOLUCAO','CONFIGURAR','CONFIGSOLUCAO.aspx')
  

Após o preenchimento ela deverá ficar conforme a Figura 2.

Figura 2. Tabela preenchida.

Vamos entender qual o sentido de cada campo da Tabela:

  • o Campo ID_MENU serve apenas como chave primária caso seja necessário ter nomes de menus repetidos;
  • o Campo NOME_MENU é o nome do menu sem conter acentos;
  • DESCR_MENU é o campo que contem a descrição que será exibida no menu;
  • HIERARQUIA_MENU é o campo onde você deve colocar o menu que é o pai deste item;
  • no campo LINK_MENU deve conter o Link do .aspx que o menu abrirá.

Agora vamos para o Visual Studio, que é a parte que realmente nos interessa na criação do menu dinâmico com CSS. Com o Visual Studio 2012 aberto acesse o menu File -> New-> project, conforme a Figura 3.

Figura 3. Iniciando novo Projeto.

Na janela seguinte digite “empty” na caixa de pesquisa e selecione BlankSolution. Altere a propriedade Name para SLMenuCSS ou para nome que preferir, conforme mostra a Figura 4.

Figura 4. Nova Solution.

Se olharmos no Solution Explorer veremos que foi criada uma solução vazia, então agora clique com o botão direito do mouse e escolha Add... e em seguida New Project.

Crie um projeto do Tipo Class Library e altere a propriedade Name para DAL, conforme demonstrado nas Figuras 5 e 6.

Figura 5.Adicionando um projeto a Solução.

Figura 6. Adicionando um projeto Class Library.

Agora vá até o Solution Explorer e clique com o botão direito do mouse sobre o projeto DAL (Class Library) escolha Add.. New item. Escolha a opção ADO.NET Entity Data Model e na propriedade Name coloque MenuModelCSS, conforme mostra as Figuras 7 e 8.

Figura 7. Adicionando um novo Item ao Projeto.

Figura 8. Adicionando ADO.Net Entity Data Model.

Agora você deve selecionar Generate from database e clicar em Next, conforme a Figura 9.

Figura 9. Opção de Geração do Entity Data Model.

Clique no botão New Connection e configure as informações conforme seu banco de dados; clique em OK. No textBox coloque MenuEntities e marque a opção “Yes, Include de Sensitive data in the connection string.”. Clique em Next, selecione a tabela Menu e clique em Finish. Os passos estão representados nas Figuras 10, 11 e 12.

Figura 10. Configurando o Banco de Dados.

Figura 11. Configurando o App.config.

Figura 12. Selecionando a Tabela.

Acesse o Solution Explorer e clique com o botão direito do mouse sobre a nossa solução e selecione Add.. New Project. Na tela que irá se abrir, escolha a opção ASP.NET Web Application e na propriedade Name coloque webMenuCSS, conforme a Figura 13.

Figura 13. Adicionando um projeto ASP.NET Web application.

Ainda no Solution Explorer clique com o botão direito do mouse sobre nosso projeto webMenu e selecione Add reference. É aqui que vamos fazer a referência do Projeto DAL; na tela que se abriu selecione a aba Project, o projeto Dal e clique em ok, conforme mostra as Figuras 14 e 15.

Figura 14. Adicionando referência.

Figura 15. Projeto DAL.

Agora no projeto menu acesse a pasta Script (caso não tenha, crie-a primeiro) clique com o botão direito do mouse e escolha add-> new item. Na janela seguinte escolha a opção JavaScript File e altere a propriedade nome para Menu.js, conforme exibido na Figura 16.

Figura 16. Adicionando JavaScript.

No arquivo js adicionado você deve inserir o código da Listagem 3.

Listagem 3. Código JavaScript


  ; (function ($, window, undefined) {
   
      'use strict';
   
      // global
      var Modernizr = window.Modernizr, $body = $('body');
   
      $.DLMenu = function (options, element) {
          this.$el = $(element);
          this._init(options);
      };
   
      // the options
      $.DLMenu.defaults = {
          
          animationClasses: { classin: 'dl-animate-in-1', classout: 'dl-animate-out-1' },
          
          onLevelClick: function (el, name) { return false; },
         
          onLinkClick: function (el, ev) { return false; }
      };
   
      $.DLMenu.prototype = {
          _init: function (options) {
   
              // options
              this.options = $.extend(true, {}, $.DLMenu.defaults, options);
              // cache some elements and initialize some variables
              this._config();
   
              var animEndEventNames = {
                  'WebkitAnimation': 'webkitAnimationEnd',
                  'OAnimation': 'oAnimationEnd',
                  'msAnimation': 'MSAnimationEnd',
                  'animation': 'animationend'
              },
                             transEndEventNames = {
                                 'WebkitTransition': 'webkitTransitionEnd',
                                 'MozTransition': 'transitionend',
                                 'OTransition': 'oTransitionEnd',
                                 'msTransition': 'MSTransitionEnd',
                                 'transition': 'transitionend'
                             };
              
              this.animEndEventName = animEndEventNames[Modernizr.prefixed('animation')] + '.dlmenu';
              
              this.transEndEventName = transEndEventNames[Modernizr.prefixed('transition')] + '.dlmenu',
              
                      this.supportAnimations = Modernizr.cssanimations,
                      this.supportTransitions = Modernizr.csstransitions;
   
              this._initEvents();
   
          },
          _config: function () {
              this.open = false;
              this.$trigger = this.$el.children('.dl-trigger');
              this.$menu = this.$el.children('ul.dl-menu');
              this.$menuitems = this.$menu.find('li:not(.dl-back)');
              this.$el.find('ul.dl-submenu').prepend('<li class="dl-back"><a href="#">back</a></li>');
              this.$back = this.$menu.find('li.dl-back');
          },
          _initEvents: function () {
   
              var self = this;
   
              this.$trigger.on('click.dlmenu', function () {
   
                  if (self.open) {
                      self._closeMenu();
                  }
                  else {
                      self._openMenu();
                  }
                  return false;
   
              });
   
              this.$menuitems.on('click.dlmenu', function (event) {
   
                  event.stopPropagation();
   
                  var $item = $(this),
                                    $submenu = $item.children('ul.dl-submenu');
   
                  if ($submenu.length > 0) {
   
                      var $flyin = $submenu.clone().css('opacity', 0).insertAfter(self.$menu),
                                          onAnimationEndFn = function () {
                                              self.$menu.off(self.animEndEventName).removeClass(self.options.animationClasses.classout).addClass('dl-subview');
                                              $item.addClass('dl-subviewopen').parents('.dl-subviewopen:first').removeClass('dl-subviewopen').addClass('dl-subview');
                                              $flyin.remove();
                                          };
   
                      setTimeout(function () {
                          $flyin.addClass(self.options.animationClasses.classin);
                          self.$menu.addClass(self.options.animationClasses.classout);
                          if (self.supportAnimations) {
                              self.$menu.on(self.animEndEventName, onAnimationEndFn);
                          }
                          else {
                              onAnimationEndFn.call();
                          }
   
                          self.options.onLevelClick($item, $item.children('a:first').text());
                      });
   
                      return false;
   
                  }
                  else {
                      self.options.onLinkClick($item, event);
                  }
   
              });
   
              this.$back.on('click.dlmenu', function (event) {
   
                  var $this = $(this),
                                    $submenu = $this.parents('ul.dl-submenu:first'),
                                    $item = $submenu.parent(),
   
                                    $flyin = $submenu.clone().insertAfter(self.$menu);
   
                  var onAnimationEndFn = function () {
                      self.$menu.off(self.animEndEventName).removeClass(self.options.animationClasses.classin);
                      $flyin.remove();
                  };
   
                  setTimeout(function () {
                      $flyin.addClass(self.options.animationClasses.classout);
                      self.$menu.addClass(self.options.animationClasses.classin);
                      if (self.supportAnimations) {
                          self.$menu.on(self.animEndEventName, onAnimationEndFn);
                      }
                      else {
                          onAnimationEndFn.call();
                      }
   
                      $item.removeClass('dl-subviewopen');
   
                      var $subview = $this.parents('.dl-subview:first');
                      if ($subview.is('li')) {
                          $subview.addClass('dl-subviewopen');
                      }
                      $subview.removeClass('dl-subview');
                  });
   
                  return false;
   
              });
   
          },
          closeMenu: function () {
              if (this.open) {
                  this._closeMenu();
              }
          },
          _closeMenu: function () {
              var self = this,
                             onTransitionEndFn = function () {
                                 self.$menu.off(self.transEndEventName);
                                 self._resetMenu();
                            };
   
              this.$menu.removeClass('dl-menuopen');
              this.$menu.addClass('dl-menu-toggle');
              this.$trigger.removeClass('dl-active');
   
              if (this.supportTransitions) {
                  this.$menu.on(this.transEndEventName, onTransitionEndFn);
              }
              else {
                  onTransitionEndFn.call();
              }
   
              this.open = false;
          },
          openMenu: function () {
              if (!this.open) {
                  this._openMenu();
              }
          },
          _openMenu: function () {
              var self = this;
              
              $body.off('click').on('click.dlmenu', function () {
                  self._closeMenu();
              });
              this.$menu.addClass('dl-menuopen dl-menu-toggle').on(this.transEndEventName, function () {
                  $(this).removeClass('dl-menu-toggle');
              });
              this.$trigger.addClass('dl-active');
              this.open = true;
          },
         
          _resetMenu: function () {
              this.$menu.removeClass('dl-subview');
              this.$menuitems.removeClass('dl-subview dl-subviewopen');
          }
      };
   
      var logError = function (message) {
          if (window.console) {
              window.console.error(message);
          }
      };
   
      $.fn.dlmenu = function (options) {
          if (typeof options === 'string') {
              var args = Array.prototype.slice.call(arguments, 1);
              this.each(function () {
                  var instance = $.data(this, 'dlmenu');
                  if (!instance) {
                      logError("cannot call methods on dlmenu prior to initialization; " +
                                    "attempted to call method '" + options + "'");
                      return;
                  }
                  if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
                      logError("no such method '" + options + "' for dlmenu instance");
                      return;
                  }
                  instance[options].apply(instance, args);
              });
          }
          else {
              this.each(function () {
                  var instance = $.data(this, 'dlmenu');
                  if (instance) {
                      instance._init();
                  }
                  else {
                      instance = $.data(this, 'dlmenu', new $.DLMenu(options, this));
                  }
              });
          }
          return this;
      };
   
  })(jQuery, window);

Esse código será responsável pela animação do nosso menu, no entanto, usando somente ele o menu é totalmente estático. Acesse o solution explorer e clique com o botão direito do mouse sobre a pasta Content e escolha add-> new item. Clique sobre Style Sheet e altere a propriedade Name para menu.css, conforme a Figura 17.

Figura 17. Arquivo CSS.

No arquivo CSS inclua o código da Listagem 4 é ele quem deixará nosso menu com uma cara mais elegante.

Listagem 4. Código CSS.


  /* Common styles of menus */
  .dl-menuwrapper {
         width: 100%;
         max-width: 300px;
         float: left;
         position: relative;
         -webkit-perspective: 1000px;
         -moz-perspective: 1000px;
         perspective: 1000px;
         -webkit-perspective-origin: 50% 200%;
         -moz-perspective-origin: 50% 200%;
         perspective-origin: 50% 200%;
   
  }
  .dl-menuwrapper:first-child {
         margin-right: 100px;
  }
  .dl-menuwrapper button 
  {
      background: #ccc;
         border: none;
         width: 48px;
         height: 45px;
         text-indent: -900em;
         overflow: hidden;
         position: relative;
         cursor: pointer;
         outline: none;
  }
  .dl-menuwrapper button:hover,
  .dl-menuwrapper button.dl-active,
  .dl-menuwrapper ul {
         background: #aaa;
  }
  /*Quadradinhos do menu*/
  .dl-menuwrapper button:after {
         content: '';
         position: absolute;
         width: 68%;
         height: 5px;
         background: #fff;
         top: 10px;
         left: 16%;
         box-shadow: 
               0 10px 0 #fff, 
               0 20px 0 #fff;
  }
  .dl-menuwrapper ul {
         padding: 0;
         list-style: none;
         -webkit-transform-style: preserve-3d;
         -moz-transform-style: preserve-3d;
         transform-style: preserve-3d;
  }
  .dl-menuwrapper li {
         position: relative;
         /*Cor do Fundo do Menu*/
         background-color: #008066;
  }
  /* links do Menu*/
  .dl-menuwrapper li a {
         display: block;
         position: relative;
         padding: 15px 20px;
         font-size: 16px;
         line-height: 20px;
         font-weight: 300;
         color: #ffffff;
         outline: none;
         text-decoration: none;
  }
  /*Quando passa o mouse por cima*/
  .no-touch .dl-menuwrapper li a:hover {
         background: rgba(255,248,213,0.1);
  }
  .dl-menuwrapper li.dl-back > a {
         padding-left: 30px;
         background: rgba(0,0,0,0.1);
  }
  /*menu back*/
  .dl-menuwrapper li.dl-back:after,
  .dl-menuwrapper li > a:not(:only-child):after {
         position: absolute;
         top: 0;
         line-height: 50px;
         font-family: 'icomoon';
         speak: none;
         -webkit-font-smoothing: antialiased;
         content: "\e000";
  }
  .dl-menuwrapper li.dl-back:after {
         left: 10px;
         color: rgba(212,204,198,0.3);
         -webkit-transform: rotate(180deg);
         -moz-transform: rotate(180deg);
         transform: rotate(180deg);
  }
  .dl-menuwrapper li > a:after {
         right: 10px;
         color: rgba(0,0,0,0.15)
  }
  .dl-menuwrapper .dl-menu {
         margin: 5px 0 0 0;
         position: absolute;
         width: 100%;
         opacity: 0;
         pointer-events: none;
         -webkit-transform: translateY(10px);
         -moz-transform: translateY(10px);
         transform: translateY(10px);
         -webkit-backface-visibility: hidden;
         -moz-backface-visibility: hidden;
         backface-visibility: hidden;
  }
  .dl-menuwrapper .dl-menu.dl-menu-toggle {
         -webkit-transition: all 0.3s ease;
         -moz-transition: all 0.3s ease;
         transition: all 0.3s ease;
  }
  .dl-menuwrapper .dl-menu.dl-menuopen {
         opacity: 1;
         pointer-events: auto;
         -webkit-transform: translateY(0px);
         -moz-transform: translateY(0px);
         transform: translateY(0px);
  }
  /* Hide the inner submenus */
  .dl-menuwrapper li .dl-submenu {
         display: none;
  }
  .dl-menu.dl-subview li,
  .dl-menu.dl-subview li.dl-subviewopen > a,
  .dl-menu.dl-subview li.dl-subview > a {
         display: none;
  }
  .dl-menu.dl-subview li.dl-subview,
  .dl-menu.dl-subview li.dl-subview .dl-submenu,
  .dl-menu.dl-subview li.dl-subviewopen,
  .dl-menu.dl-subview li.dl-subviewopen > .dl-submenu,
  .dl-menu.dl-subview li.dl-subviewopen > .dl-submenu > li {
         display: block;
  }
  /* Dynamically added submenu outside of the menu context */
  .dl-menuwrapper > .dl-submenu {
         position: absolute;
         width: 100%;
         top: 50px;
         left: 0;
         margin: 0;
  }
  /* Animation classes for moving out and in */
  .dl-menu.dl-animate-out-5 {
         -webkit-animation: MenuAnimOut5 0.4s ease;
         -moz-animation: MenuAnimOut5 0.4s ease;
         animation: MenuAnimOut5 0.4s ease;
  }
  @-webkit-keyframes MenuAnimOut5 {
         100% {
               -webkit-transform: translateY(40%);
               opacity: 0;
         }
  }
  @-moz-keyframes MenuAnimOut5 {
         100% {
               -moz-transform: translateY(40%);
               opacity: 0;
         }
  }
  @keyframes MenuAnimOut5 {
         100% {
               transform: translateY(40%);
               opacity: 0;
         }
  }
  .dl-menu.dl-animate-in-5 {
         -webkit-animation: MenuAnimIn5 0.4s ease;
         -moz-animation: MenuAnimIn5 0.4s ease;
         animation: MenuAnimIn5 0.4s ease;
  }
  @-webkit-keyframes MenuAnimIn5 {
         0% {
               -webkit-transform: translateY(40%);
               opacity: 0;
         }
         100% {
               -webkit-transform: translateY(0);
               opacity: 1;
         }
  }
  @-moz-keyframes MenuAnimIn5 {
         0% {
               -moz-transform: translateY(40%);
               opacity: 0;
         }
         100% {
               -moz-transform: translateY(0);
               opacity: 1;
         }
  }
  @keyframes MenuAnimIn5 {
         0% {
               transform: translateY(40%);
               opacity: 0;
         }
         100% {
               transform: translateY(0);
               opacity: 1;
         }
  }
  .dl-menuwrapper > .dl-submenu.dl-animate-in-5 {
         -webkit-animation: SubMenuAnimIn5 0.4s ease;
         -moz-animation: SubMenuAnimIn5 0.4s ease;
         animation: SubMenuAnimIn5 0.4s ease;
  }
  @-webkit-keyframes SubMenuAnimIn5 {
         0% {
               -webkit-transform: translateZ(-200px);
               opacity: 0;
         }
         100% {
               -webkit-transform: translateZ(0);
               opacity: 1;
         }
  }
  @-moz-keyframes SubMenuAnimIn5 {
         0% {
               -moz-transform: translateZ(-200px);
               opacity: 0;
         }
         100% {
               -moz-transform: translateZ(0);
               opacity: 1;
         }
  }
  @keyframes SubMenuAnimIn5 {
         0% {
               transform: translateZ(-200px);
               opacity: 0;
         }
         100% {
               transform: translateZ(0);
               opacity: 1;
         }
  }
  .dl-menuwrapper > .dl-submenu.dl-animate-out-5 {
         -webkit-animation: SubMenuAnimOut5 0.4s ease;
         -moz-animation: SubMenuAnimOut5 0.4s ease;
         animation: SubMenuAnimOut5 0.4s ease;
  }
  @-webkit-keyframes SubMenuAnimOut5 {
         0% {
               -webkit-transform: translateZ(0);
               opacity: 1;
         }
         100% {
               -webkit-transform: translateZ(-200px);
               opacity: 0;
         }
  }
  @-moz-keyframes SubMenuAnimOut5 {
         0% {
               -moz-transform: translateZ(0);
               opacity: 1;
         }
         100% {
               -moz-transform: translateZ(-200px);
               opacity: 0;
         }
  }
  @keyframes SubMenuAnimOut5 {
         0% {
               transform: translateZ(0);
               opacity: 1;
         }
         100% {
               transform: translateZ(-200px);
               opacity: 0;
         }
  }
  /* No JS Fallback */
  .no-js .dl-menuwrapper .dl-menu {
         position: relative;
         opacity: 1;
         -webkit-transform: none;
         -moz-transform: none;
         transform: none;
  }
  .no-js .dl-menuwrapper li .dl-submenu {
         display: block;
  }
   
  .no-js .dl-menuwrapper li.dl-back {
         display: none;
  }
  .no-js .dl-menuwrapper li > a:not(:only-child) {
         background: rgba(0,0,0,0.1);
  }
   
  .no-js .dl-menuwrapper li > a:not(:only-child):after {
         content: '';
  }
  /* Colors for demos */
  /* Demo 3 */
  .demo-3 .dl-menuwrapper button {
         background: #008066;
  }
  /*Cor do Menu quando passa o mouse sobre*/
  .demo-3 .dl-menuwrapper button:hover,
  .demo-3 .dl-menuwrapper button.dl-active,
  .demo-3 .dl-menuwrapper ul {
         background: #00b4ae;
  }

Agora adicione um novo Web Form acessando o solution explorer, clicando sobre o projeto web esolha a opção add -> Web Form e nomeie-o de Default.aspx, conforme ilustrado na Figura 18.

Figura 18. Adicionando Web Form

Vamos alterar a TAG e deixá-la conforme a Listagem 5. Você verá que além do js que criamos o código abaixo irá referenciar um js (jquery) através do https do google api, e o outro você pode realizar o download neste link.

Listagem 5. Código tag.


  <head runat="server">
      <title></title>
      
      <link href="Content/menu.css" rel="stylesheet" />
   
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
   
      <script src="Script/modernizr.custom.js"></script>
   
      <script src="Script/menu.js"></script>
   
      <script type="text/javascript">
   
          $(function () {
              $('#dl-menu').dlmenu({
                  animationClasses: { classin: 'dl-animate-in-5', classout: 'dl-animate-out-5' }
              });
          });
   
      </script>
   
  </head>

Vamos agora substituir a tag , conforme Listagem 6. Com isso, terminamos a parte gráfica.

Listagem 6.Código body


  <body>
      <form id="form1" runat="server">
          <div class="container demo-3">                      
              <div id="dl-menu" class="dl-menuwrapper">
                       <button class="dl-trigger">Open Menu</button>
                       <ul class="dl-menu">
                          <asp:Literal ID="lit" runat="server">           
                    </asp:Literal>
                        </ul>
                 </div><!-- /dl-menuwrapper -->
          </div><!-- /container -->
      </form>
  </body>

Adicione duas nova classes ao seu projeto e altere seus respectivos nomes para HierarquiaMenu.cs e lHierarquiaMenu.cs. Após isso, insira os códigos das Listagens 7 e 8 em seus respectivos arquivos .cs.

Listagem 7. Código HierearquiaMenu


      public class HierarquiaMenu : MENU
      {
          public lHierarquiaMenu Children { get; set; }
   
          public HierarquiaMenu()
          {
              Children = new lHierarquiaMenu();
          }
      }

Listagem 8. Código lHierearquiaMenu


      public class lHierarquiaMenu:List<HierarquiaMenu>
      {
          public lHierarquiaMenu()
          {
          }
   
          public lHierarquiaMenu(List<MENU> lmenu)
          {
   
              //lHierarquiaMenu _lHierarquiaMenu;
   
              foreach (var menu in lmenu)
              {
                  if (menu.HIERARQUIA_MENU != null)
                  {
                      HierarquiaMenu hmpai = this.BuscaMenu(menu.HIERARQUIA_MENU);
                      HierarquiaMenu hm = new HierarquiaMenu();
                      hm.ID_MENU = menu.ID_MENU;
                      hm.LINK_MENU = menu.LINK_MENU;
                      hm.NOME_MENU = menu.NOME_MENU;
                      hm.HIERARQUIA_MENU = menu.HIERARQUIA_MENU;
                      hm.DESCR_MENU = menu.DESCR_MENU;
   
   
                      hmpai.Children.Add(hm);
                  }
                  else
                  {
                      HierarquiaMenu hm = new HierarquiaMenu();
                      hm.ID_MENU = menu.ID_MENU;
                      hm.LINK_MENU = menu.LINK_MENU;
                      hm.NOME_MENU = menu.NOME_MENU;
                      hm.HIERARQUIA_MENU = menu.HIERARQUIA_MENU;
                      hm.DESCR_MENU = menu.DESCR_MENU;
   
   
                      this.Add(hm);
                  }
              }
   
              //return _lHierarquiaMenu;
          }
   
          public HierarquiaMenu BuscaMenu(string Nome)
          {
              return BuscaMenu(this, Nome);
          }
   
          public HierarquiaMenu BuscaMenu(lHierarquiaMenu lMenu, string Nome)
          {
              foreach (var menu in lMenu)
              {
                  if (menu.NOME_MENU == Nome)
                  {
                      return menu;
                  }
                  else if (menu.Children.Count > 0)
                  {
                      HierarquiaMenu hm = BuscaMenu(menu.Children, Nome);
                      if (hm != null)
                      {
                          return hm;
                      }
                  }
              }
   
              return null;
          }
   
          public string CriaMenu()
          {
              string sMenu = "";
              CriaMenu(this, ref sMenu, 0);
              return sMenu;
          }
   
          public void CriaMenu(lHierarquiaMenu _lMenuHieraquia, ref string sMenu, int ColocaUL)
          {
   
              foreach (var menu in _lMenuHieraquia)
              {
                  if (string.IsNullOrEmpty(sMenu))
                  {
                      sMenu = "<li>";
                  }
                  else
                  {
                      sMenu += "<li>";
                  }
                  sMenu += @"<a href=""";
                  sMenu += menu.LINK_MENU;
                  sMenu += @""">";
                  sMenu += menu.DESCR_MENU;
                  sMenu += "</a>";
                  if (menu.Children.Count > 0)
                  {
                      sMenu += @"   <ul class=""dl-submenu"">";
                      CriaMenu(menu.Children, ref sMenu, 1);
                  }
                  sMenu += "</li>";
              }
   
              if (ColocaUL == 1)
              {
                  sMenu += "</ul>";
              }
          }
      }

Por último, abra o arquivo Default.aspx.cs e no método Page_Load e insira o código, conforme a Listagem 9.

Listagem 9. Código page_load


  protected void Page_Load(object sender, EventArgs e)
          {
              if (!IsPostBack)
              {
                  TutoriaisEntities t = new TutoriaisEntities();
   
                  lHierarquiaMenu _lhm = new lHierarquiaMenu(t.MENU.OrderBy(m => m.HIERARQUIA_MENU).ToList());
   
                  string meCSS = _lhm.CriaMenu();
   
                  lit.Text = meCSS;
              }
          }

Com isso, finalizamos nosso projeto agora. É só executar a aplicação e ver o resultado que deverá ser, como nas Figuras 19, 20 e 21.

Figura 19. Resultado Final

Figura 20. Clicando no Menu.

Figura 21. Clicando em configurar.

Com o projeto acima apresentado você conseguirá criar menus dinâmicos com os formatos que necessitar bastando apenas trocar os arquivos CSS e JS para que seja alterado o designer do menu de acordo com sua necessidade.

Ficamos por aqui com mais um post, espero que gostem e até a próxima.