views:

1528

answers:

5

I am trying to come up with the best way to render some hierarchical data in to a nested unordered list using ASP.NET MVC. Does anyone have any tips on how to do this?

+1  A: 

You mean... you want some sort of tree view?

You can actually get the treeview control to work... but you have to wrap it in server side form tag to function. You'll get the usual nastiness that that brings (like generated ids and viewstate) but it will work from a rendering perspective.

If you want to just create tags and nest them, it would be pretty easy to do with foreach() loops.

Ben Scheirman
+1  A: 

I suggest jquery tree view plugins for making it function like a tree, but as for render, just put it in a recursive lambda helper to do the nesting.

DevelopingChris
jquery for a treecontrol sounds like a good idea, thanks for the suggestion. Could you elaborate on how to use a recursive lambda for rendering.
Joel Cunningham
A: 

For that (rendering hierarchical menu, treeview, etc) i use recursive calls of custom component (ascx, or aspx in new preview5).
I give component first level of items (List of items), and component then check for each item in list if there's any child items and call itself with list of that child items.
You can build hierarchical graph of objects in controller, or just 1 dimensional list with ParentID property.

Hrvoje
+1  A: 

I believe currently there is no such control.... TreeViews are complex by nature. You can of course "draw" a hierarchy as much as you like using all sorts of repeaters and loops, but to achieve functionality of a tree view like the one in the Web forms toolbox... you have to wait !

+1  A: 

Why don't you pass your model in the form of a tree to the view?

/// This is the model class
public class MyTreeNode<T>
{
    public ICollection<MyTreeNode> ChildNodes {get;}
    public T MyValue { get; set; }
    bool HasChildren { get { return ChildNodes.Any(); } }
}

///This is the html helper:
public static string RenderTree<T>(this HtmlHelper html, MyTreeNode<T> root, Func<T, string> renderNode)
{
    var sb = new StringBuilder();
    sb.Append(renderNode(root.MyValue));
    if (root.HasChildren)
    {
        foreach(var child in root.ChildNodes)
        {
            sb.Append(RenderTree<T>(html, child, renderNode));
        }
    }
    return sb.ToString();
}

I didn't actually test this code, but it's about the idea. You can imagine creating your own recursive html helper to render a tree.

Paco
Well put ... you need to add some usercontrol that does the rendering while integrating with jquery treeview plugin for maximum features... Still need some enhancement on node formatting... for example if it should render as a link ... thx
jalchr