Search results

Data binding

The TreeGrid uses DataManager, which supports both RESTful JSON data services binding and local JavaScript object array binding. The dataSource property can be assigned either with the instance of DataManager or JavaScript object array collection. It supports two kinds of data binding method:

  • Local data
  • Remote data

Local Data

In Local Data binding, data source for rendering the TreeGrid control is retrieved from the same application locally.

Two types of Data binding are possible with the TreeGrid control.

  • Hierarchical Datasource binding
  • Self-Referential Data binding (Flat Data)

To bind local data to the treegrid, you can assign a JavaScript object array to the dataSource property. The local data source can also be provided as an instance of the DataManager.

By default, DataManager uses JsonAdaptor for local data-binding.

Hierarchy data source binding

The childMapping property is used to map the child records in hierarchy data source.

The following code example shows you how to bind the hierarchical local data into the TreeGrid control.

tagHelper
hierarchy.cs
<ejs-treegrid id="TreeGrid" dataSource="@ViewBag.data" allowPaging="true" childMapping="Children" treeColumnIndex="1">
    <e-treegrid-pagesettings pageSize="7"></e-treegrid-pagesettings>
    <e-treegrid-columns>
        <e-treegrid-column field="TaskId" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" 
                format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.data = tree;
    return View();
}

Self-Referential Data binding (Flat Data)

TreeGrid is rendered from Self-Referential data structures by providing two fields, ID field and parent ID field.

  • ID Field: This field contains unique values used to identify nodes. Its name is assigned to the idMapping property.
  • Parent ID Field: This field contains values that indicate parent nodes. Its name is assigned to the parentIdMapping property.
tagHelper
selfdata.cs
<ejs-treegrid id="TreeGrid" dataSource="@ViewBag.data" idMapping="TaskId" parentIdMapping='ParentId' allowPaging="true" childMapping="Children" treeColumnIndex="1">
    <e-treegrid-pagesettings pageSize="7"></e-treegrid-pagesettings>
    <e-treegrid-columns>
        <e-treegrid-column field="TaskId" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" 
                format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>
public IActionResult Index()
{
    var tree = TreeData.GetSelfData();
    ViewBag.data = tree;
    return View();
}

Remote data

To bind remote data to TreeGrid component, assign service data as an instance of DataManager to the dataSource property. To interact with remote data source, provide the endpoint url and define the hasChildMapping property of treegrid.

The TreeGrid provides Load on Demand support for rendering remote data. The Load on demand is considered in TreeGrid for the following actions.

  • Expanding root nodes.
  • Navigating pages, with paging enabled in TreeGrid.

When load on demand is enabled, all the root nodes are rendered in collapsed state at initial load.

When load on demand support is enabled in TreeGrid with paging, the current or active page’s root node alone will be rendered in collapsed state. On expanding the root node, the child nodes will be loaded from the remote server.

When a root node is expanded, its child nodes are rendered and are cached locally, such that on consecutive expand/collapse actions on root node, the child nodes are loaded from the cache instead from the remote server.

Similarly, if the user navigates to a new page, the root nodes of that specific page, will be rendered with request to the remote server.

tagHelper
remote.cs
<ejs-treegrid id="TreeGrid" idMapping="TaskID" height="260" parentIdMapping="ParentItem"  hasChildMapping="isParent" treeColumnIndex="1">
  <e-data-manager url="https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData" adaptor="WebApiAdaptor" crossDomain="true"></e-data-manager>
  <e-treegrid-columns>
    <e-treegrid-column field="TaskID" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
    <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
    <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" 
      format="yMd" type="date" width="90"></e-treegrid-column>
    <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
  </e-treegrid-columns>
</ejs-treegrid>
public IActionResult Index()
{
    return View();
}

By default, DataManager uses ODataAdaptor for remote data-binding. Based on the RESTful web services, set the corresponding adaptor to DataManager. Refer here for more details. Filtering and searching server-side data operations are not supported in load on demand

Offline Mode

On remote data binding, all treegrid actions such as paging, loading child on-demand, will be processed on server-side. To avoid postback, set the treegrid to load all data on initialization and make the actions process in client-side. To enable this behavior, use the offline property of DataManager.

tagHelper
offline.cs
<ejs-treegrid id="TreeGrid" idMapping="TaskID" height="260" parentIdMapping="ParentItem" treeColumnIndex="1">
  <e-data-manager url="https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData" adaptor="WebApiAdaptor" offline="true" crossDomain="true"></e-data-manager>
    <e-treegrid-columns>
      <e-treegrid-column field="TaskID" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
      <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
      <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" 
        format="yMd" type="date" width="90"></e-treegrid-column>
      <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>
public IActionResult Index()
{
    return View();
}

Custom Adaptor

You can create your own adaptor by extending the built-in adaptors. The following demonstrates custom adaptor approach and how to add a serial number for the records by overriding the built-in response processing using the processResponse method of the ODataAdaptor.

tagHelper
custom.cs
<ejs-treegrid id="TreeGrid" idMapping="TaskID" parentIdMapping="ParentItem" created="created" treeColumnIndex="1">
    <e-treegrid-columns>
        <e-treegrid-column field="TaskID" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right"
                           format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>

<script>
    function created(args) {
        class SerialNoAdaptor extends ej.data.ODataAdaptor {
            processResponse() {
                var i = 0;
                // calling base class processResponse function
                var original = super.processResponse.apply(this, arguments);
                // adding serial number
                if (!ej.base.isNullOrUndefined(original.result)) {
                    original.result.forEach(function (item) { item['Sno'] = ++i });
                    return { result: original.result, count: original.count };
                }
                else
                    return original;
            }
        }
        var treegrid = document.querySelector('#TreeGrid').ej2_instances[0];
        treegrid.dataSource = new ej.data.DataManager({
            url: "https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData",
            adaptor: new SerialNoAdaptor()
        });
    }
</script>
public IActionResult Index()
{
    return View();
}

Sending additional parameters to the server

To add a custom parameter to the data request, use the addParams method of Query class. Assign the Query object with additional parameters to the treegrid query property.

tagHelper
addparam.cs
<ejs-treegrid id="TreeGrid" idMapping="TaskID" query="new ej.data.Query().addParams('ej2treegrid', 'true')" height="260" parentIdMapping="ParentItem" treeColumnIndex="1" hasChildMapping="isParent">
    <e-data-manager url="https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData" adaptor="WebApiAdaptor" crossDomain="true"></e-data-manager>
      <e-treegrid-columns>
        <e-treegrid-column field="TaskID" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" 
                format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>
public IActionResult Index()
{
    return View();
}

Handling HTTP error

During server interaction from the treegrid, some server-side exceptions may occur, and you can acquire those error messages or exception details in client-side using the actionFailure event.

The argument passed to the actionFailure event contains the error details returned from the server.

tagHelper
failure.cs
<ejs-treegrid id="TreeGrid" idMapping="TaskID" parentIdMapping="ParentItem" actionFailure="actionFailure" treeColumnIndex="1" hasChildMapping="isParent">
    <e-data-manager url="http://some.com/invalidUrl"></e-data-manager>
      <e-treegrid-columns>
        <e-treegrid-column field="TaskID" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" 
                format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>

<script>
    function actionFailure(e) {
       var span = document.createElement('span');
       this.element.parentNode.insertBefore(span, this.element);
       span.style.color = '#FF0000'
       span.innerHTML = 'Server exception: 404 Not found';
    }
</script>
public IActionResult Index()
{
    return View();
}

The actionFailure event will be triggered not only for the server errors, but also when there is an exception while processing the treegrid actions.

Binding with Ajax

You can use TreeGrid dataSource property to bind the data source to TreeGrid from external Ajax request. In the below code we have fetched the data source from the server with the help of Ajax request and provided that to dataSource property by using onSuccess event of the Ajax.

tagHelper
ajax.cs
<ejs-button id="updateTree" content="Update TreeGrid"></ejs-button>

<ejs-treegrid id="TreeGrid" idMapping="TaskID" parentIdMapping="ParentItem" allowPaging="true" treeColumnIndex="1" hasChildMapping="isParent">
    <e-treegrid-pagesettings pageSize="7"></e-treegrid-pagesettings>
    <e-treegrid-columns>
        <e-treegrid-column field="TaskID" headerText="Task ID" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right"
                           format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>

<script>
    document.getElementById("updateTree").addEventListener("click", function (e) {
        var treegrid = document.getElementById('TreeGrid').ej2_instances[0];
        var ajax = new ej.base.Ajax('https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData', 'GET');
        treegrid.showSpinner();
        ajax.send();
        ajax.onSuccess = function (data) {
            treegrid.hideSpinner();
            treegrid.dataSource = JSON.parse(data);
        };
    });
</script>
public IActionResult Index()
{
    return View();
}
  • If you bind the dataSource from this way, then it acts like a local dataSource. So you cannot perform any server side crud actions.