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.

razor
local-data.cs
@Html.EJS().TreeGrid("LocalData").DataSource((IEnumerable<object>)ViewBag.datasource).Columns(col =>
{
  col.Field("TaskId").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
  col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
  col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging(true).PageSettings(p => p.PageSize(7)).ChildMapping("Children").TreeColumnIndex(1).Render()
public ActionResult LocalData()
{
    var treeData = TreeGridItems.GetTreeData();
    ViewBag.datasource = treeData;
    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.

razor
self-reference.cs
@Html.EJS().TreeGrid("SelfReferenceData").DataSource((IEnumerable<object>)ViewBag.datasource).Columns(col =>
{
  col.Field("TaskId").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
  col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
  col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).IdMapping("TaskId").ParentIdMapping("ParentId").AllowPaging().PageSettings(p => p.PageSize(7)).TreeColumnIndex(1).Render()
public ActionResult SelfReferenceData()
  {
    var treeData = TreeData.GetSelfDataSource();
    ViewBag.datasource = treeData;
    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.

razor
remote-data.cs
@Html.EJS().TreeGrid("RemoteData").DataSource(dataManager => dataManager.Url("https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData").Adaptor("WebApiAdaptor").CrossDomain(true)).Columns(col =>
{
   col.Field("TaskID").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
   col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
   col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).HasChildMapping("isParent").Height(260).IdMapping("TaskID").ParentIdMapping("ParentItem").AllowPaging().TreeColumnIndex(1).Render()
public ActionResult RemoteData()
{
  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.

razor
offline.cs
@Html.EJS().TreeGrid("RemoteData").DataSource(dataManager => dataManager.Url("https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData").Adaptor("WebApiAdaptor").CrossDomain(true).Offline(true)).Columns(col =>
{
   col.Field("TaskID").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
   col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
   col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).HasChildMapping("isParent").Height(260).IdMapping("TaskID").ParentIdMapping("ParentItem").AllowPaging().TreeColumnIndex(1).Render()
public ActionResult Offline()
{
  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.

razor
customadaptor.cs
@Html.EJS().TreeGrid("TreeGrid").Columns(col =>
{
   col.Field("TaskID").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
   col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
   col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).HasChildMapping("isParent").Height(260).IdMapping("TaskID").ParentIdMapping("ParentItem").Created("created").TreeColumnIndex(1).Render()

<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 ActionResult CustomAdaptor()
{
  return View();
}

Sending additional parameters to the server

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

razor
@Html.EJS().TreeGrid("Params").DataSource(dataManager => dataManager.Url("https://ej2services.syncfusion.com/production/web-services/api/SelfReferenceData").Adaptor("WebApiAdaptor").CrossDomain(true)).Columns(col =>
{
   col.Field("TaskID").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
   col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
   col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).IdMapping("TaskID").ParentIdMapping("ParentItem").Height(260).AllowPaging().Query("new ej.data.Query().addParams('ej2TreeGrid', 'true')").TreeColumnIndex(1).Render()

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.

razor
http-error.cs
@Html.EJS().TreeGrid("HttpError").DataSource(dataManager => { dataManager.Url("http://some.com/invalidUrl"); }).Columns(col =>
{
   col.Field("TaskID").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
   col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
   col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).IdMapping("TaskID").ParentIdMapping("ParentItem").ActionFailure("actionFailure").TreeColumnIndex(1).Render()

<script>
    function actionFailure(args) {
        var treegrid = document.getElementById("HttpError").ej2_instances[0];
        var span = document.createElement('span');
        treegrid.element.parentNode.insertBefore(span, treegrid.element);
        span.style.color = '#FF0000'
        span.innerHTML = 'Server exception: 404 Not found';
    }
</script>
public ActionResult HttpError()
{
  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.

razor
ajaxbind.cs
@Html.EJS().Button("button").Content("Bind Data").Render()

@Html.EJS().TreeGrid("Ajax").Columns(col =>
{
   col.Field("TaskID").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
   col.Field("StartDate").HeaderText("Start Date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
   col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).IdMapping("TaskID").ParentIdMapping("ParentItem").AllowPaging().PageSettings(p => p.PageSize(7)).TreeColumnIndex(1).Render()

<script>
    document.getElementById("button").addEventListener('click', () => {
        var treegrid = document.getElementById("Ajax").ej2_instances[0];
        treegrid.element.parentNode.insertBefore(button, treegrid.element);
        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 ActionResult AjaxBind()
{
  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.