Skip to main content

Bind Tree List to Data

  • 3 minutes to read

The DevExpress ASP.NET MVC TreeList extension supports binding to an object that supports the IEnumerable or IQueryable interface. Since TreeList is designed to display information in a tree structure, its data source should meet certain requirements. If a data source contains flat data, two additional fields are necessary to build a tree structure:

Columns bound to these fields are called service columns.

Important

When TreeList is bound to a hierarchical data source (e.g. XmlDataSource), the TreeListSettings.KeyFieldName and TreeListSettings.ParentFieldName properties are not in effect.

The following steps describe how to add the TreeList extension to your project and bind it to data.

Step 1. Create a Data Model

Create a new data model. You can use any model that supports the IEnumerable or IQueryable interface. For example, you can create a new model using the Entity Framework Code First or Entity Framework Database First development approach.

Step 2. Add a TreeList to the View

The TreeList updates its content via callbacks. Since ASP.NET MVC does not support callbacks, you will need to place the TreeList in the Partial View and define how the callbacks will be routed back to your controller using the TreeListSettings.CallbackRouteValues property.

View code:

@model IList<Department>

@Html.Partial("DataBindingPartial", Model)

Partial View code (“DataBindingPartial.cshtml”):

@Html.DevExpress().TreeList(settings => {
    settings.Name = "treeList";

    // The "OverviewPartial" action from the HomeController will handle the TreeList callbacks.
    settings.CallbackRouteValues = new { Controller = "Home", Action = "DataBindingPartial" };

    // Defining the key field and parent field names.
    settings.KeyFieldName = "ID";
    settings.ParentFieldName = "ParentID";

    // Adding columns for the required data fields.
    settings.Columns.Add("Department");
    settings.Columns.Add("Budget").PropertiesEdit.DisplayFormatString = "{0:C}";
    settings.Columns.Add("Location");
}).Bind(Model).GetHtml()

Step 3. Edit the Controller Code

Within the controller code, you will need to define the action method that will handle the TreeList’s callbacks. The “DataBindingPartial” action method below handles the callbacks. The DepartmentsModel.GetData method gets the data from the data source to pass to the View.

Controller code:

using System;
using System.Linq;
using System.Web.Mvc;

namespace MyProject.Controllers
{
    public class HomeController : Controller
    {
        MyProject.Models.DepartmentsModel db = new MyProject.Models.DepartmentsModel();

        public ActionResult Index()
        {
            return View(db.GetData());
        }

        public ActionResult DataBindingPartial()
        {
            return PartialView(db.GetData());
        }
    }
}

The image below shows the result.

TreeList_BindingToData

See Also