0

If I have the below table in SQL Server. Is there a way for me to load it into a Kendo ui MVC treeview? All the demos on their site have static tree nodes. I attempted, but it somehow does doesn't group things together.

Id Name ParentId

1 USA NULL

2 Texas 1

3 Houston 2

4 Katy 3

5 Spring 3

6 Florida 1

7 Tallahassee 6

8 Massachusetts 1

9 Boston 8

10 Springfield 9

Here's my attempt to populated the tree: Controller:

var modelsList = new List<TreeModel>();
        var connString = ConfigurationManager.ConnectionStrings["DefaultConnection"];

        using (var conn = new SqlConnection(connString.ToString()))
        using (var sqlCmd = new SqlCommand("SELECT Id, Name, ParentId FROM tblTree ", conn))
        {                               
            conn.Open();
            SqlDataReader reader = sqlCmd.ExecuteReader();
            while (reader.Read())
            {
                int id2 = Convert.ToInt32(reader["Id"]);
                string attributeName = reader["AttributeName"].ToString();
                var parentId = reader["ParentId"];
                var model = new TreeModel();
                model.Id = id2;
                model.Name = attributeName;
                if (parentId != DBNull.Value)
                    model.hasChildren = Convert.ToInt32(parentId);
                else
                    model.hasChildren = 0;

                modelsList.Add(model);
            }

        }

        return Json(modelsList, JsonRequestBehavior.AllowGet);
tereško
  • 58,060
  • 25
  • 98
  • 150
AnhLun
  • 25
  • 2
  • 2
  • 11

1 Answers1

1

You'll need to convert your list into a hierarchical data structure, so that each node has an array of child nodes (the tree view will inspect model.items by default, but you can customize the field name). Here's a post on how you might do that on the server-side. Unfortunately, there currently is no way to specify a parent id field which would automate this for you (although I'd suggest raising this issue in the feedback forum, since the question has come up a number of times now).

Community
  • 1
  • 1
Lars Höppner
  • 18,252
  • 2
  • 45
  • 73