How to filter the tree nodes in TreeView for ASP.Net MVC when using ViewBag.datasource as the datasource?

Controller:

public ActionResult Index()
{
using (var context = Data.DatabaseContext())
{
   List<CategoryDataListView> categoriesList = //get from db table;
   List<object> listdata = new List<object>();
   foreach (var item in categoriesList)
   {
      listdata.Add(new
      {
        id = item.CategoryID,
        pid = item.ParentID,
        name = item.Name,
        hasChild = (item.ParentID != 0) ? false : true
     });
   }
   ViewBag.dataSource = listdata;
 }
   return View();
}

View:

 <div>

 @*CATEGORY TREE VIEW*@

@Html.EJS().TreeView("listdata").ShowCheckBox(true).Fields(field => field.Id("id").ParentID("pid").Selected("selected").Expanded("expanded").Text("name").HasChildren("hasChild").DataSource(ViewBag.dataSource)).Render();
 
</div>

3 Replies

PM Prasanth Madhaiyan Syncfusion Team July 22, 2022 10:44 AM UTC

Hi Rasmiya,


Greetings from Syncfusion support.


We have validated your reported query in the ASP.NET MVC TreeView component by preparing the sample. We understand that you want to perform the filtering operation in the TreeView component by using ViewBag.datasource as the data source. For your reference, we have performed a filtering operation on a hierarchical data source in the TreeView component using the MaskedTextBox change event and you need to store the matched node of the search string in an object array and assign this value to TreeView datasource.


Refer to the below code snippet.


[index.cshtml]

 

    <div class="main-menu">

        <div class="table-content">

            @Html.EJS().MaskedTextBox("search").Placeholder("Search").Change("searchNodes").Render()

            <p class="main-menu-header">TABLE OF CONTENTS</p>

        </div>

        <div>

            <!-- Treeview element declaration-->

            @Html.EJS().TreeView("main-treeview").Fields(ViewBag.fields).ExpandOn(Syncfusion.EJ2.Navigations.ExpandOnSettings.Click).Render()

 

        </div>

    </div>

    <!-- end of normal state element declaration -->

</div>).Render();}

        <!-- end of sidebar element -->

 

    </div>

</div>

<script>

  var original=[];

  var ignoreAccent = false;

    function searchNodes(args) {

        var treeObj = document.getElementById("main-treeview").ej2_instances[0];

          if(!ignoreAccent){

            original= treeObj.getTreeData();

            ignoreAccent=true

          }

          else{

              var matchedDataSource= [];

               var  treeData= JSON.parse(JSON.stringify(original));

              for (let i = 0; i < treeData.length; i++) {

                    //Search the nested child node of TreeView component.

                    let filteredChild = nestedChildFilter(args.value, treeData[i]);

                    if (filteredChild !== null) { matchedDataSource.push(filteredChild); }

              }

              // After searching the entire TreeView data and change the datasource of TreeView component.

              treeObj.fields = { dataSource: matchedDataSource , id: 'nodeId', text: 'nodeText', child: 'child'};

          }

     }

    function nestedChildFilter(value, node) {

        var treeObj = document.getElementById("main-treeview").ej2_instances[0];

        // If the child node contain children

        let children= node[treeObj.fields.child];

        if (children == null) {

            return (isMatchedNode(value, node)) ? node : null;

        } else {

            let matchedChildren = [];

            for (let i = 0; i < children.length; i++) {

                // You can again search the child node of TreeView component.

                let filteredChild = nestedChildFilter(value, children[i]);

                if (filteredChild !== null) { matchedChildren.push(filteredChild); }

            }

            if (matchedChildren.length !== 0) {

                node[treeObj.fields.child] = matchedChildren;

                return node;

            } else {

                node[treeObj.fields.child] = null;

                return (isMatchedNode(value, node)) ? node : null;

            }

        }

    }

    function isMatchedNode(value, node) {

       var treeObj = document.getElementById("main-treeview").ej2_instances[0];

            let checkValue = node[treeObj.fields.text];

            checkValue = checkValue.toLowerCase();

            value = value.toLowerCase();

            return checkValue.indexOf(value) !== -1;

        }

</script>


For your reference, we have attached the sample.


Sample : https://www.syncfusion.com/downloads/support/directtrac/general/ze/TreeViewFiltering-841790886.zip


Please check the shared sample and let us know if you any further assistance.


Regards,

Prasanth Madhaiyan.




RN Rasmiya Najeem replied to Prasanth Madhaiyan July 24, 2022 06:50 AM UTC

Hi Prasanth,

Thank you for the quick response. The functions are working, but after changing the datasource the treeview is rendered I can see the div in the elements, but the nodes are not displayed.


Can you also tell me how I can use DataManager or Predicates in ASP.Net MVC treeview?



PM Prasanth Madhaiyan Syncfusion Team July 25, 2022 07:33 AM UTC

Hi Rasmiya,


We have validated your reported query in the TreeView component. We were not clear because previously you wanted to perform the filtering operation by fetching the data from ViewBag.datasource and now you want to perform the filtering operation using the DataManager (remote date) service.


For your reference, we have attached the remote date documentation and demo link.


Documentation : https://ej2.syncfusion.com/aspnetmvc/documentation/treeview/data-binding?cs-save-lang=1&cs-lang=razor#remote-data


Demo : https://ej2.syncfusion.com/aspnetmvc/TreeView/RemoteData#/fluent


We have not rendered the child nodes in the initial rendering and it fetches the child nodes on a load-on-demand basis. When you perform the filtering operation using the remote data in the TreeView component, you must set the loadOnDemand as false.


If further assistance is required, please provide the details of the adaptor being used to bind the data source at your end. These details will help us to check and provide a prompt solution.


Regards,

Prasanth Madhaiyan.


Loader.
Up arrow icon