title: Loop Through Multi-Level Dynamic Menus in Asp.Net MVC
body: <p>i am trying to loop through multilevel dynamic menus. I have been succeeded to do this manually i.e everytime if want to display the child <code>Menus</code> of it's parent, I have to loop manually. <strong>I would like to know the best way or an alternative of looping multi-level through these dynamic menus</strong>
  Here is what i have done so far;</p>
  
  <pre><code>@{ var menusList = ViewBag.Menus as IEnumerable&lt;ParentMenuViewModel&gt;; }
  @foreach (var parentMenu in menusList.Where(p =&gt; p.ParentId == 0))
  {
      &lt;ul&gt;
          &lt;li&gt;
              &lt;h1&gt;@parentMenu.Name&lt;/h1&gt;
              @if (menusList.Count(p =&gt; p.ParentId == parentMenu.MenuId) &gt; 0)
              {
                  &lt;ul&gt;
                      @foreach (var childMenu in menusList.Where(p =&gt; p.ParentId == parentMenu.MenuId))
                      {
                          &lt;h2&gt;@childMenu.Name&lt;/h2&gt;
                          if (menusList.Count(p =&gt; p.ParentId == childMenu.MenuId) &gt; 0)
                          {
                              foreach (var subChild in menusList.Where(p =&gt; p.ParentId == childMenu.MenuId))
                              {
                                  &lt;h3&gt;@subChild.Name&lt;/h3&gt;
                              }
                          }
                      }
                  &lt;/ul&gt;
              }
          &lt;/li&gt;
      &lt;/ul&gt;
  
  }
  </code></pre>
  
  <p><strong>UPDATE:</strong> The output looks like this;</p>
  
  <pre><code>HOME
   SUB MENU1
    SUB SUB MENU1
    SUB SUB MENU2
  </code></pre>
  
  <p>However, i have in my database something like this;</p>
  
  <pre><code>HOME
   SUB MENU1
    SUB SUB MENU1
    SUB SUB MENU2
      Sub SUB SUB MENU1
      Sub SUB SUB MENU2
  </code></pre>
  
  <p>Here is my model;<br />
  <img src="https://i.stack.imgur.com/69nsu.png" alt="enter image description here"></p>