mmushtaq mmushtaq - 6 months ago 171
C# Question

Creating Three Levels Tree View using FancyTree

Problem: I am working on a MVC project where I have to integrate FancyTree. I need to bind data to FancyTree from Database. In its documentation, Load tree from Ajax JSON Demo is also avaiable as follow:

$("#tree2").fancytree({
source: {
url: "ajax-tree-plain.json"
},
lazyload: function(e, data){
// we can't return values from an event handler, so we
// pass the result as `data`attribute.
// data.result = {url: "unit/ajax-sub2.json"};
data.result = $.ajax({
url: "ajax-sub2.json",
dataType: "json"
});
}
});


and its output is :

FancyTree Demo

So my requirement is that how can I process data and bind it to FancyTree which contains TreeView structure of my
CategoryName
,
Model Name
and
Provider Name
which should be looks like this:

CategoryName - 1
Model Name - 1
Provider Name - 1
CategoryName - 2
Model Name - 2
Provider Name - 2
CategoryName - 3
Model Name - 3
Provider Name - 3


And a Checkbox should be display with each node of TreeView.

I have found This Question useful for my scenario but the proposed solution does not meet my requirements as it is not so clear to me and does not contain any code example.

Any help would be greatly appreciated. Thanks

Answer

I think you need something like this:

public class Category
{
    public string Name { get; set; }
    public List<CarModel> CarModels = new List<CarModel>();
}

public class CarModel
{
    public string Name { get; set; }
    public List<Provider> Providers = new List<Provider>();
}

public class Provider
{
    public string Name { get; set; }
}

Your data would look like this:

var categories = new List<Category>()
{
    new Category()
    {
        Name = "OP",
        CarModels = new List<CarModel>()
        {
            new CarModel()
            {
                Name = "YN555",
                Providers = new List<Provider>()
                {
                    new Provider()
                    {
                        Name = "US",
                    }
                },
            },
        },
    },
    new Category()
    {
        Name = "AS",
        CarModels = new List<CarModel>()
        {
            new CarModel()
            {
                Name = "UP222",
                Providers = new List<Provider>()
                {
                    new Provider()
                    {
                        Name = "PK",
                    }
                },
            },
        },
    },
};

categories