Check/Uncheck on TreeView Node Click in ASP.NET MVC

21 Aug 20265 minutes to read

You can check and uncheck the checkboxes of TreeView by clicking the tree node using the nodeClicked event of TreeView.

@Html.EJS().TreeView("treedata").ShowCheckBox(true).NodeClicked("nodeCheck").KeyPress("nodeCheck").Fields(field=>
    field.Id("id").ParentID("pid").Text("name").HasChildren("hasChild").Expanded("expanded")
    .Selected("is_selected").HtmlAttributes("hasAttribute").DataSource(ViewBag.dataSource)).Render()

<script>
    function nodeCheck(args) {
        var checkedNode = [args.node];
        var treeObj = document.getElementById('treedata').ej2_instances[0];
        if (args.event.target.classList.contains('e-fullrow') || args.event.key == "Enter") {
            var getNodeDetails = treeObj.getNode(args.node);
            if (getNodeDetails.isChecked == 'true') {
                treeObj.uncheckAll(checkedNode);
            } else {
                treeObj.checkAll(checkedNode);
            }
        }
    }
</script>
using Syncfusion.EJ2.Navigations;

public ActionResult CheckUncheck()
{
    List<object> treedata = new List<object>();
    treedata.Add(new { id = 1, name = "Australia", hasChild = true, expanded = true });
    treedata.Add(new { id = 2, pid = 1, name = "New South Wales", });
    treedata.Add(new { id = 3, pid = 1, name = "Victoria" });
    treedata.Add(new { id = 4, pid = 1, name = "South Australia" });
    treedata.Add(new { id = 6, pid = 1, name = "Western Australia", });
    treedata.Add(new { id = 7, name = "Brazil", hasChild = true });
    treedata.Add(new { id = 8, pid = 7, name = "ParanĂ¡" });
    treedata.Add(new { id = 9, pid = 7, name = "CearĂ¡" });
    treedata.Add(new { id = 10, pid = 7, name = "Acre" });
    treedata.Add(new { id = 11, name = "China", hasChild = true });
    treedata.Add(new { id = 12, pid = 11, name = "Guangzhou" });
    treedata.Add(new { id = 13, pid = 11, name = "Shanghai" });
    treedata.Add(new { id = 14, pid = 11, name = "Beijing" });
    treedata.Add(new { id = 15, pid = 11, name = "Shantou" });
    treedata.Add(new { id = 16, name = "France", hasChild = true });
    treedata.Add(new { id = 17, pid = 16, name = "Pays de la Loire" });
    treedata.Add(new { id = 18, pid = 16, name = "Aquitaine" });
    treedata.Add(new { id = 19, pid = 16, name = "Brittany" });
    treedata.Add(new { id = 20, pid = 16, name = "Lorraine" });
    treedata.Add(new { id = 21, name = "India", hasChild = true });
    treedata.Add(new { id = 22, pid = 21, name = "Assam" });
    treedata.Add(new { id = 23, pid = 21, name = "Bihar" });
    treedata.Add(new { id = 24, pid = 21, name = "Tamil Nadu" });
    ViewBag.dataSource = treedata;
    return View();
}

The output will look like the image below:

TreeView Sample