asp.net-mvcjsonjquery-easyui

A circular reference was detected while serializing an object of type?


DB MetersTree TABLE

id       text   parentId    state

 0       root          0     open
 1    level 1          1     open
 2    level 1          1     open
 ...     

CONTROLLER

public ActionResult GetDemoTree()
{
    OsosPlus2DbEntities entity = new OsosPlus2DbEntities();
    MetersTree meterTree = entity.MetersTree.FirstOrDefault();

    return Json(meterTree, JsonRequestBehavior.AllowGet);
}

DATA FORMAT THAT SHOULD BE (for example)

[{  
    "id": 1,  
    "text": "Node 1",  
    "state": "closed",  
    "children": [{  
        "id": 11,  
        "text": "Node 11"  
    },{  
        "id": 12,  
        "text": "Node 12"  
    }]  
},{  
    "id": 2,  
    "text": "Node 2",  
    "state": "closed"  
}]  

How can I create tree Json Data? If I write MetersTree with its relationships I get the error that is defined in the title.


Solution

  • I solved it like this:

    VIEW MODEL

    public class MetersTreeViewModel
    {
        public int id { get; set; }
        public string text { get; set; }
        public string state { get; set; }
        public bool @checked { get; set; }
        public string attributes { get; set; }
        public List<MetersTreeViewModel> children { get; set; }
    }
    

    CONTROLLER

    public ActionResult GetMetersTree()
    {
        MetersTree meterTreeFromDb = entity.MetersTree.SingleOrDefault(x => x.sno == 5); //in my db this is the root.
        List<MetersTreeViewModel> metersTreeToView = buildTree(meterTreeFromDb.Children).ToList();
    
        return Json(metersTreeToView, JsonRequestBehavior.AllowGet);
    }
    

    BuildTree Method

    private List<MetersTreeViewModel> BuildTree(IEnumerable<MetersTree> treeFromDb)
    {
        List<MetersTreeViewModel> metersTreeNodes = new List<MetersTreeViewModel>();
        foreach (var node in treeFromDb)
        {
            if (node.Children.Any())
            {
                metersTreeNodes.Add(new MetersTreeViewModel
                {
                    id = node.sno,
                    text = node.Text,
                    state = node.Text,
                    children = BuildTree(node.Children)
                });
            }
            else {
                metersTreeNodes.Add(new MetersTreeViewModel
                {
                    id = node.sno,
                    text = node.Text,
                    state = node.Text
                });
            }
        }
    
        return metersTreeNodes;
    }
    

    Thanks to all who are interested in ...