I am using JSTree with a MVC project and I am trying to add child nodes to the tree, however I am getting a null refference error Object reference not set to an instance of an object on the line subGroupNode.children.Add(itemNode);
I guess this is because the subGroupNode.Children
is empty. how can it be when the child is created in the previous foreach loop.
public JsonResult GetJsTree3Data()
{
var marketGroups = new List<JsTree3Node>();
// Create our root node and ensure it is opened
var root = new JsTree3Node()
{
id = Guid.NewGuid().ToString(),
text = "Market Items",
state = new State(true, false, false)
};
foreach (var group in GenerateGroups(connString))
{
if (group.marketParentGroup == 0)
{
var node = JsTree3Node.NewNode(group.id_str);
node.text = group.name;
node.state = new State(false, false, false);
marketGroups.Add(node);
}
}
foreach (var marketGroup in marketGroups)
{
foreach (var subGroup in GenerateGroups(connString))
{
if (subGroup.marketParentGroup.ToString() == marketGroup.id)
{
var childNodes = new List<JsTree3Node>();
var childNode = new JsTree3Node();
childNode.id = subGroup.id_str;
childNode.text = subGroup.name;
childNode.state = new State(false, false, false);
childNodes.Add(childNode);
var subGroupNode = new JsTree3Node();
subGroupNode.id = subGroup.id_str;
subGroupNode.text = subGroup.name;
subGroupNode.state = new State(false, false, false);
subGroupNode.children = childNodes;
marketGroup.children.Add(subGroupNode);
}
}
}
return Json(root, JsonRequestBehavior.AllowGet);
}
I solved the issue by creating a second list the same as the first and comparing those two lists.