In previous article, I have mentioned Treeview in ASP.NET MVC, now in this article, I have provided working example to create treeview in ASP.NET Core MVC and how to get selected treeview nodes in C# Controller.

Step 1: Create a new ASP.NET Core MVC project in your Visual Studio, by navigating to File -> New -> Project -> Select "Web" from left-pane and ASP.NET Core MVC web application from right-pane.

Name it, and select MVC template from second screen so Visual Studio can generate .NET core MVC template for you.

Step 2: Create new a Model inside "Treeview.cs" "Models" folder, so right-click on the folder, select "Add" and then select "Class", name it "Treeview.cs" and use the below code

using System.Collections.Generic;

namespace TreeViewInAspNetCore.Models
{
    public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int StateId { get; set; }
        public virtual State State { get; set; }
    }

    public class State
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public virtual List<City> City { get; set; }
    }

    public class TreeViewNode
    {
        public string id { get; set; }
        public string parent { get; set; }
        public string text { get; set; }
    }
}

In the above Model class, as you can see we will be creating Main Node as "TreeViewNode" and then sub-node as "State" and then child node as "City".

So in this Model, we will be adding data using C# manually, not dynamic data from database, but you can easily fetch data from database also and push it in the List, once the code is clear.

So, I am keeping it simple and will be adding List data using C# code.

Step 3: Navigate to "HomeController.cs" and use the below code to create TreeView Nodes and get submitted values of Nodes.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using TreeViewInAspNetCore.Models;

namespace TreeViewInAspNetCore.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            List<TreeViewNode> nodes = new List<TreeViewNode>();

            //add parent nodes
            nodes.Add(new TreeViewNode { id = "1", parent = "#", text = "Rajasthan" });
            nodes.Add(new TreeViewNode { id = "2", parent = "#", text = "Gujrat" });


            //add child nodes for first parent
            nodes.Add(new TreeViewNode { id = "11", parent = "1", text = "Jaipur" });
            nodes.Add(new TreeViewNode { id = "12" , parent = "1", text = "Ajmer" });

            //add child nodes for second parent
            nodes.Add(new TreeViewNode { id = "21", parent = "2", text = "Baroda" });
            nodes.Add(new TreeViewNode { id = "22", parent = "2", text = "Surat" });


            //Serialize to JSON string.
            ViewBag.Json = JsonConvert.SerializeObject(nodes);
            return View();
        }

        [HttpPost]
        public ActionResult Index(string selectedItems)
        {
            List<TreeViewNode> items = JsonConvert.DeserializeObject<List<TreeViewNode>>(selectedItems);
            return RedirectToAction("Index");
        }

    }
}

I have commented out important lines of code.

Basically, In the above code, we are creating Index Actionmethod and inside which we will be creating TreeView Nodes.

At first, we are adding main parent-nodes

           //add parent nodes
            nodes.Add(new TreeViewNode { id = "1", parent = "#", text = "Rajasthan" });
            nodes.Add(new TreeViewNode { id = "2", parent = "#", text = "Gujrat" });

Then since we have added 2 States, which will be parent, so parent id = "#" in the above code, now considering these state's Id, we are adding city into it

           //add child nodes for first parent
            nodes.Add(new TreeViewNode { id = "11", parent = "1", text = "Jaipur" });
            nodes.Add(new TreeViewNode { id = "12" , parent = "1", text = "Ajmer" });

            //add child nodes for second parent
            nodes.Add(new TreeViewNode { id = "21", parent = "2", text = "Baroda" });
            nodes.Add(new TreeViewNode { id = "22", parent = "2", text = "Surat" });

Then Seriliazing it as JSON to pass it on to the view.

We have also created "httppost" ActionMethod, so get selected and submitted treeview value in this ActionMethod.

Step 4: Naviagte to "Index.cshtml" inside "Views" -> "Home" and use the below code to generate Treeview from above code.

@{
    ViewData["Title"] = "Home Page";
}

<div id="jstree">
</div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <input type="hidden" name="selectedItems" id="selectedItems" />
    <input type="submit" value="Submit" />
}

@section scripts{
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#jstree').on('changed.jstree', function (e, data) {
                var i, j;
                var postedItems = [];
                for(i = 0, j = data.selected.length; i < j; i++) {

                    //Fetch the Id.
                    var id = data.selected[i];

                    //Add the Node to the JSON Array.
                    postedItems.push({
                        text: data.instance.get_node(data.selected[i]).text,
                        id: id,
                        parent: data.node.parents[0]
                    });
                }

                //Serialize the JSON Array and save in HiddenField.
                $('#selectedItems').val(JSON.stringify(postedItems));
            }).jstree({
                "core": {
                    "themes": {
                        "variant": "large"
                    },
                    "data": @Html.Raw(ViewBag.Json)
                    },
                "checkbox": {
                    "keep_selected_style": false
                },
                "plugins": ["wholerow", "checkbox"],
            });
        });
    </script>
}

In the above code, we have created a div for generate treeview with id "jstree"

And, we have created a form to save selected values using Html.BeginForm.

Rest if the JS code, to initialize treeview and push selected item values in Form as Hidden value "selectedItems" using below code

                var i, j;
                var postedItems = [];
                for(i = 0, j = data.selected.length; i < j; i++) {

                    //Fetch the Id.
                    var id = data.selected[i];

                    //Add the Node to the JSON Array.
                    postedItems.push({
                        text: data.instance.get_node(data.selected[i]).text,
                        id: id,
                        parent: data.node.parents[0]
                    });
                }

                //Serialize the JSON Array and save in HiddenField.
                $('#selectedItems').val(JSON.stringify(postedItems));

That's it, we are done, build and run the code in browser, you will see output like below

treeview-asp-net-core-mvc-js-tree-view-min.gif

You can see Treeview output in the above gif image on page load and when submitting selected value to C# controller, we are able to fetch correct selected values in back-end side.

You may also like to read

File Upload in ASP.NET Core MVC (Single and Multiple)

Form Submit in ASP.NET Core MVC

Model Validation in ASP.NET Core MVC

Creating GridView in ASP.NET Core MVC with Paging

Import Excel data in SQL Server database in ASP.NET Core MVC

jQuery AJAX in ASP.NET Core MVC