Articles in this section

Submit a form with ASP.NET MVC TreeView’s checked nodes

The knowledge base article explains how to retrieve checked nodes from TreeView and submit it with form.

The ASP.NET MVC TreeView is not a form component, so you cannot retrieve the TreeView node values directly through form actions. You can achieve this requirement by using the below steps.

Get Started with ASP.NET MVC TreeView

Create a ASP.NET MVC application and integrate TreeView control - https://ej2.syncfusion.com/aspnetmvc/documentation/treeview/getting-started

TreeView with CheckBox in ASP.NET MVC Form

Create a Form and render the TreeView component with DataSource and corresponding field mapping. And enable the checkbox using ‘ShowCheckBox’ property.

@using (Html.BeginForm("PostUsingParameter", "Home"))
{
    @Html.EJS().TreeView("treedata").NodeChecked("nodeChecked").EnablePersistence(true).ShowCheckBox(true).Fields(field =>
    field.Id("id").ParentID("pid").Text("name").HasChildren("hasChild").Expanded("expanded")
    .DataSource(ViewBag.dataSource)).Render()
 
    <input type="submit" value="save" onclick="onSave()" />
    <input type="button" value="Reset" onclick="onReset()" />
} 

 

Add Input element to store the checked nodes

Creating a hidden input and updating the value while checking the tree nodes using the NodeChecked event

@using (Html.BeginForm("PostUsingParameter", "Home"))
{
    <input type="hidden" name="checkTree" id="checkTree">
    @Html.EJS().TreeView("treedata").NodeChecked("nodeChecked").EnablePersistence(true).ShowCheckBox(true).Fields(field =>
    field.Id("id").ParentID("pid").Text("name").HasChildren("hasChild").Expanded("expanded")
    .DataSource(ViewBag.dataSource)).Render()
 
    <input type="submit" value="save" onclick="onSave()" />
    <input type="button" value="Reset" onclick="onReset()" />
}
<script>
    function nodeChecked(args) {
        var treeObj = document.getElementById('treedata').ej2_instances[0];
        //You can get the checked node details using the getAllCheckedNodes method.
        var data = treeObj.getAllCheckedNodes();
        // In the hidden input, update the details of the checked nodes.
        $("#checkTree").val(data);
    }
    function onReset() {
        var treeObj = document.getElementById('treedata').ej2_instances[0];
        //To reset, you can uncheck the TreeView checked node using the uncheckAll method.
        treeObj.uncheckAll();
    }
</script> 

 

Receive the checked node details in the controller

At the server end, you can receive the checked node’s data using name of the input element.

[HttpPost]
public string PostUsingParameter(string checkTree)
{
  return checkTree;
}

 

GitHub sample - https://github.com/SyncfusionExamples/aspnetmvc-treeview-checked-nodes-form

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied