Parent / Child (hierarchical) relational treeview display in Dot Net (MVC) with C#

Introduction:

This article explains parent / Child (hierarchical) relational tree view display with example.
Data Base Table-


---------------------------------------------------------------------------------------------------------


[Serializable]
    [Table("meTreeViewStructure")]
    public class TreeViewStructure
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int TreeViewID { get; set; }
        public string AadharID { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
        public string Parent_AadharID { get; set; }
        public string Parent_Name { get; set; }
        public string Parent_Designation { get; set; }
        public string Description { get; set; }
    }
    [Serializable]
    public class MyClass
    {
        public int ID;
        public int ParentID;
        public List<MyClass> Children = new List<MyClass>();
        public MyClass(int id, int parent_id)
        {
            ID = id;
            ParentID = parent_id;
        }
    }

--------------------------------------------------------------------------------------------------------- 

initialize sample data from database

----------------------------------------------------------------------------------------------------------

 public ActionResult GetTreeViewStructure()
 
{
 
var Result=(List<TreeViewStructure>)Helper.ExecuteService("eFile","GetData",null);

List<MyClass> items = new List<MyClass>();

foreach (var item in Result)
{

 items.Add(new MyClass(Convert.ToInt32(item.AadharID),
Convert.ToInt32(item.Parent_AadharID))); 
 
}
 
items.ForEach(item => item.Children = items.Where(child => child.ParentID == item.ID)
                                           .ToList());
List<MyClass> topItems = items.Where(item => item.ParentID == 0).ToList(); 
 
return new JsonResult { 
 
Data = topItems, ContentType = "Json"
JsonRequestBehavior = JsonRequestBehavior.AllowGet 
  }; 
///It return List in Json Format.
 
}
 
--------------------------------------------------------------------------
 
Output :-

JsonResult-
[{"ID":1,"ParentID":0,"Children":[{"ID":1001,"ParentID":1,"Children":[{"ID":1004,"ParentID":1001,"Children":[]}]},{"ID":1002,"ParentID":1,"Children":[{"ID":1005,"ParentID":1002,"Children":[]}]},{"ID":1003,"ParentID":1,"Children":[]}]}]

  Tree view Display:

Dependency:

Treed : JavaScript Tree Editor


Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment