Question

I have a database similar to this:

| Element_ID               | Element_Parent                |  
|____________1_____________|_______________0_______________|  
|____________2_____________|_______________0_______________|  
|____________3_____________|_______________1_______________|  
|____________4_____________|_______________3_______________|  
|____________5_____________|_______________3_______________|  
|____________6_____________|_______________2_______________|  
|____________7_____________|_______________6_______________|  
|____________8_____________|_______________6_______________|  

Where the Element_Parent refers to the Element_ID column and 0 means that the element does not have a parent.

I need to display the database entries similar to this:

<ul>
    <li>
        1
        <ul>
            <li>
                3
                <ul>
                    <li>4</li>
                    <li>5</li>
                </ul>
            </li>
        </ul>
    </li>

    <li>
        2
        <ul>
            <li>
                6
                <ul>
                    <li>7</li>
                    <li>8</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I am accessing the database using DynamicRecords.

Was it helpful?

Solution

If you want a server side solution, you should be able to get something useful from this article I wrote on using recursion in ASP.NET Web Pages: http://www.mikesdotnetting.com/Article/208/Practical-Recursion-in-ASP.NET-Web-Pages-with-WebMatrix.

But in essence, you need a helper something like this:

@helper  BuildTreeView(IEnumerable<dynamic> data, int? parentid = null, int level = 0) {
    var nodes = data.Where(n => n.ParentId == parentid).OrderBy(n => n.DisplayOrder);
    if (nodes.Any()) {
        if(nodes.First().ParentId != null){
            level++;
        }
        foreach (var node in nodes) {
            <div style="padding-left:@(level * 20)px;">
                @node.Text
            </div>
            @BuildTreeView(data, node.Id, level);
        }
    }
}

I've added a DisplayOrder column so that you can add and remove items from your database and still control the order in which they are displayed in their individual nodes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top