recursion function for generating menu in C#

Jak
Jak
Member
858 Points
132 Posts

Hi,

I am working arround menu. I need to generate html multi level menu (using ul/li tags). I have following menu table

MenuID MenuName ParentMenuID Link
1 about us NULL  
2 services NULL  
3 about company 1  
4 goal of company 1  
5 technical consult 2  
6 contact us NULL  

..like that.

I want recursive function to generate menu with all child as: 

<ul> 
<li>contact us</li> 
<li>about us 
<ul> 
<li>about company</li> 
<li>goal of company</li> 
</ul> 
</li> 
<li>services 
<ul> 
<li>technical consult 
<ul> 
<li>For you</li> 
</ul> 
</li> 
</ul> 
</li> 
</ul>
Views: 10250
Total Answered: 1
Total Marked As Answer: 0
Posted On: 15-Jan-2016 00:19

Share:   fb twitter linkedin
Answers
beginer
beginer
Member
1328 Points
43 Posts
         

Use following logic to build menu

private HtmlGenericControl RenderMenu(Nodes nodes)
{
    if (nodes == null)
        return null;

    var ul = new HtmlGenericControl("ul");

    foreach (Node node in nodes)
    {
        var li = new HtmlGenericControl("li");
        li.InnerText = node.Name;

        if(node.Children != null)
        {
            li.Controls.Add(RenderMenu(node.Children));
        }

        ul.Controls.Add(li);
    }

    return ul;
}
Posted On: 27-Dec-2017 06:26
 Log In to Chat