Search code examples
jsonasp.net-mvcjqtree

Use jqTree with ASP MVC and JSON File


I have just added jqTree to my ASP MVC app. I need to display a TreeView in my view:

@{
    ViewBag.Title = "Tree";
}

<h2>@ViewBag.Title</h2>

<div id="tree1" data-url="/Home/Nodes"></div>

@section scripts {
    <script language="javascript" type="text/javascript">
        $(function () {
            $('#tree1').tree();
        });
    </script>
}

My data is in a JSON file (~/App_Data/Roles.json):

{
    "id": 1,
    "label": "Role1",
    "children": [
        {
            "id": 2,
            "label": "Role2",
            "children": [
                {
                    "id": 3,
                    "label": "Role3",
                    "children": [
                    ]
                },
                {
                    "id": 4,
                    "label": "Role4",
                    "children": [
                    ]
                }
            ]
        }
    ]
}

How do I load the json file in the controller action method to display corresponding TreeView in the view?

public ActionResult Nodes()
{
    var roles = // load json file

    return Json(roles, JsonRequestBehavior.AllowGet);
}

Solution

  • You can pass the json from JSON file(~/App_Data/Roles.json) and create the tree in the following way:

    Add the below code in your view:

    <div id="tree1"></div>
    
    @section scripts {
        <script language="javascript" type="text/javascript">
            $.ajax({
                type: 'POST', // we are sending data so this is POST
                traditional: true, 
                url: '/Home/Nodes', // controller/action name
                success: function (d) {
                    $('#tree1').tree({
                        data: [jQuery.parseJSON(d)]
                    });
                }
            });
        </script>
    }
    

    Create a Nodes() function in your HomeController as:

    public ActionResult Nodes()
        {
            string roles = string.Empty;
            using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Roles.json")))
            {
                roles = r.ReadToEnd();
            }                 
            return Json(roles, JsonRequestBehavior.AllowGet);
        }
    

    And you will be able to view your tree. Please let me know if you face any issues.