Articles in this section
Category / Section

How to Maintain the State of the ASP.NET MVC TreeView?

3 mins read

Description

The state of the TreeView nodes are changed to default when the page is refreshed or on any post-back operations. You can maintain the state of nodes by restoring the data from browser cookies.

Solution

In order to maintain the state of TreeView after rebinding the source or on page refresh, you can store the TreeView node state in client-side script on every TreeView action and restore them back on TreeView load. Using the jQuery cookies function you can store the value in browser cookies, so refer the jQuery cookies script in your application.

Now define a script function to store the expanded and selected TreeView nodes in variables respectively and assign the function to ClientSideOnNodeExpand, ClientSideOnNodeClick and ClientSideOnNodeCollapse events. Similarly define a function to restore the state of TreeView and assign it to ClientSideOnLoaded event. So that the TreeView changes are stored using the client-side events and restored from cookies.

CSHTML

@Html.Syncfusion().TreeView("MyTreeView", "DataBind", ((TreeViewModel)ViewData["myTreeViewModel"]))

Client-side JavaScript

<script src="~/Scripts/jquery-cookie.js" type="text/javascript"></script>
<script type="text/javascript">
    var ExpandedNodesId = $.cookie('ExpandedNodesCollection');
    var SelectedNodeId = $.cookie('SelectedNode');
    var data="Treeview";
    function updateTree() {
        //Expanding the nodes
        ExpandedNodesId = ExpandedNodesId != null ? ExpandedNodesId.split(';') : [];
        var treeviewObj = $find("MyTreeView");
        $.each(ExpandedNodesId, function (index, value) {
            treeviewObj.ExpandNode(value);
        });
        //selecting the nodes
        if (SelectedNodeId != null)
            treeviewObj.SelectNode(SelectedNodeId);
    }
    function PersistTreeviewState(sender, args) {
        //persisting the Node expand/collapse state
        if (args._isExpanded) {
            if ($.inArray(args._id, ExpandedNodesId) < 0)
                ExpandedNodesId.push(args._id);
        }
        else
            Array.remove(ExpandedNodesId, args._id);
        $.cookie('ExpandedNodesCollection', ExpandedNodesId.join(';'));
        //persisting the Node select/unselect state
        if (args._isSelected)
            SelectedNodeId = args._id;
        $.cookie('SelectedNode', SelectedNodeId);
    }
</script>

Controller, C#

public ActionResult ToolsFeatures()
{
    ViewData["ProductName"] = "Tools";
    // Binding datasource for treeview
    List<TreeList> TreeLists = new List<TreeList> { 
        new TreeList {ID= 1, ParentID=null, FolderName = "ASP.NET"}, 
        new TreeList {ID = 12, ParentID =  1 , FolderName = "Essential Tools"},
        new TreeList {ID = 13, ParentID =  1, FolderName = "Essential Grid"},
        new TreeList {ID = 14, ParentID =  1, FolderName = "Essential Schedule"},
        new TreeList {ID = 15, ParentID =  1, FolderName = "Essential Gauge"},
        new TreeList {ID= 2, ParentID=null, FolderName = "Backoffice products"}, 
        new TreeList {ID = 21, ParentID =  2 , FolderName = "Essential PDF"},
        new TreeList {ID = 31, ParentID =  2, FolderName = "Essential XlsIO"},
        new TreeList {ID = 41, ParentID =  2, FolderName = "Essential DocIO"},
        new TreeList {ID = 51, ParentID =  2, FolderName = "Essential Calculate"},
        new TreeList {ID= 3, ParentID=null, FolderName = "SilverLight"}, 
        new TreeList {ID = 22, ParentID =  3 , FolderName = "Essential Tools"},
        new TreeList {ID = 32, ParentID =  3, FolderName = "Essential Gauge"},
        new TreeList {ID = 42, ParentID =  3, FolderName = "Essential Chart"},
        new TreeList {ID = 52, ParentID =  3, FolderName = "Essential Grid"},
        new TreeList {ID= 4, ParentID=null, FolderName = "WPF"}, 
        new TreeList {ID = 23, ParentID =  4 , FolderName = "Essential Edit"},
        new TreeList {ID = 33, ParentID =  4, FolderName = "Essential HTML UI"},
        new TreeList {ID = 43, ParentID =  4, FolderName = "Essential Grid"},
        new TreeList {ID = 53, ParentID =  4, FolderName = "Essential Tools"}
    };
    TreeViewFields treeViewFields = new TreeViewFields()
    {
        Id = "ID",
        ParentId = "ParentID",
        Text = "FolderName",
    };
    // Defining treeview model to map the fields and events
    Syncfusion.Mvc.Tools.TreeViewModel treemodel = new Syncfusion.Mvc.Tools.TreeViewModel();
    {
        treemodel.DataSource = TreeLists.ToList();
        treemodel.BindTo = treeViewFields;
        treemodel.ClientSideOnLoaded = "updateTree";
        treemodel.ClientSideOnNodeClick = "PersistTreeviewState";
        treemodel.ClientSideOnNodeExpand = "PersistTreeviewState";
        treemodel.ClientSideOnNodeCollapse = "PersistTreeviewState";
    };
    ViewData["myTreeViewModel"] = treemodel;
    return View();
}
public class TreeList
{
    public int ID { get; set; }
    public int? ParentID { get; set; }
    public string FolderName { get; set; }
}

 

Refer the following online demo for references,


Conclusion

I hope you enjoyed learning about how to maintain the state of the ASP.NET MVC TreeView?.

You can refer to our ASP.NET MVC TreeView page to know about its other groundbreaking feature representations. You can also explore our ASP.NET MVC TreeView Documentation to understand how to manipulate data.

For current customers you can check out on our ASP.NET MVC components from the License and Download page. If you are new to Syncfusion, you can try our 30-day free trial to check out our ASP.NET MVC TreeView  and other ASP.NET MVC components.

If you have any queries or require clarifications, please let us know in the comment section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!


Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied