New to Telerik UI for ASP.NET Core? Download free 30-day trial

Save the State of TreeView Items

Environment

Product Telerik UI for ASP.NET Core TreeView
Product Version Created with version 2024.4.1112

Description

How can I save the expanded and checked state of the TreeView items on the server and preserve it the next time the data is loaded?

Solution

  1. Define a TreeView that binds to remote data and handle its Change event.
@(Html.Kendo().TreeView()
    .Name("treeview")
    .Checkboxes(true)
    .DataTextField("Name")
    .DataSource(dataSource => dataSource
        .Read(read => read
            .Action("Read", "Home")
        )
        .Model(model =>
        {
            model.Id("ID");
            model.HasChildren("HasChildren");
        })
        .Events(events => events.Change("OnChange"))
    )
)
<kendo-treeview datatextfield="name" name="treeview" on-change="OnChange">
    <hierarchical-datasource>
        <schema>
            <hierarchical-model id="ID" children="HasChildren"></hierarchical-model>
        </schema>
        <transport>
            <read url="@Url.Action("Read", "Home")" />
        </transport>
    </hierarchical-datasource>
    <checkboxes enabled="true"/>
</kendo-treeview>
function OnChange(e) {
        if (e.action == "itemchange") {
            var item = e.items[0];
            $.post('@Url.Action("Save", "Home")', { // Submit an AJAX request to the server and send the current state of the selected item.
                id: item.id,
                isChecked: item.checked,
                expanded: item.expanded
            });
        }

}
public void Save(int id, bool isChecked, bool expanded)
{
    UpdateModel(data.First(v => v.ID == id));
}

For a runnable example, refer to the ASP.NET MVC application in the UI for ASP.NET MVC Examples repository. You can use this as a starting point to configure the same behavior in an ASP.NET Core project.

More ASP.NET Core TreeView Resources

See Also

In this article