code_junkie

Hierarchical Data In ASP.NET MVC

Nov 10th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. /// This is the model class
  2. public class MyTreeNode<T>
  3. {
  4. public ICollection<MyTreeNode> ChildNodes {get;}
  5. public T MyValue { get; set; }
  6. bool HasChildren { get { return ChildNodes.Any(); } }
  7. }
  8.  
  9. ///This is the html helper:
  10. public static string RenderTree<T>(this HtmlHelper html, MyTreeNode<T> root, Func<T, string> renderNode)
  11. {
  12. var sb = new StringBuilder();
  13. sb.Append(renderNode(root.MyValue));
  14. if (root.HasChildren)
  15. {
  16. foreach(var child in root.ChildNodes)
  17. {
  18. sb.Append(RenderTree<T>(html, child, renderNode));
  19. }
  20. }
  21. return sb.ToString();
  22. }
Add Comment
Please, Sign In to add comment