This is a migrated thread and some comments may be shown as answers.
Custom treeview population
1 Answer 41 Views
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Shane
Top achievements
Rank 1
Shane asked on 18 Feb 2011, 02:08 AM
Hello,

I'm trying to recursively populate the treeview based on the data I've been provided in a table.

Basically, its a menu structure where the table is as follows:

ID, Text, ParentID

Root nodes have a parentID of -1, and children have their parentID set to the ID of their parent.

I'm trying to recursively do this however I cannot seem to get far with the binding examples, or really, any of the population examples I've seen. Can someone point me in the right direction on manually creating a TreeViewItemFactory that I can just set as the data source for the TreeView?

Regards,

Shane

1 Answer, 1 is accepted

Sort by
0
Shane
Top achievements
Rank 1
answered on 18 Feb 2011, 04:47 AM
Hello,

Managed to sort this by binding to a JSON object, which is returned from the server:

This is the menu structure class:

public class JsonMenuStructure
{
    public string Text { get; set; }
    public bool Expanded { get; set; }
    public List<JsonMenuStructure> Items { get; set; }
}

This is the code that renders the objects:

public static string RenderMenus()
{
    List<JsonMenuStructure> rootMenuList = new List<JsonMenuStructure>();
 
    IEnumerable<Menus> rootMenus =
        GetAll().Where(mi => mi.ParentID == -1);
 
    foreach (Menus rootMenu in rootMenus)
    {
        rootMenuList.Add(new JsonMenuStructure() { Text = rootMenu.Text, Expanded = true, Items = GetChildMenus(rootMenu.ID) });
    }
 
    return Json.Encode(rootMenuList);
}
 
public static List<JsonMenuStructure> GetChildMenus(int parentID)
{
    List<JsonMenuStructure> menuItemList = new List<JsonMenuStructure>();
 
    IEnumerable<Menus> subItems =
        GetAll().Where(mi => mi.ParentID == parentID);
 
    foreach (Menus subItem in subItems)
    {
        menuItemList.Add(new JsonMenuStructure() { Text = subItem.Text, Expanded = true, Items = GetChildMenus(subItem.ID) });
    }
 
    return menuItemList;

And finally I render the JSON string to the view:

<script type="text/javascript">
    function onDataBinding(e) {
        var treeview = $('#menuTreeView').data('tTreeView');
 
        var jsonObject =
            @MvcHtmlString.Create(Website.Models.Managers.MenusManager.RenderMenus())
            ;
 
        treeview.bindTo(jsonObject);
    }
 
</script>


..bit of a workaround. I'll be cleaning the code up but thats basically it! Hope I helped someone..

Shane
Tags
TreeView
Asked by
Shane
Top achievements
Rank 1
Answers by
Shane
Top achievements
Rank 1
Share this question
or