Save the State of TreeView Items
Environment
Product | Telerik UI for ASP.NET MVC 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
- 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"))
)
)
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.