I have a self referencing data structure and I want to show this data in my UI layer as a Tree View.
My Model Class looks like:
public class Person
{
public Person()
{
Children = new List<Person>();
}
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual Person Parent { get; set; }
public virtual List<Person> Children { get; set; }
}
My action method in my controller class is look like:
public IActionResult HierarchicalDataStructure()
{
var people = new PersonListModel(_context)
{
People = _context.People.Include(i => i.Children).ToList()
};
return View(people);
}
After few tries I've decided to solve this problem with tag helpers(which I couldnt =) ) So my TagHelper class is looks like:
public override void Process(TagHelperContext context, TagHelperOutput output)
{
PeopleTreeView(context, output);
base.Process(context, output);
}
void PeopleTreeView(TagHelperContext context, TagHelperOutput output)
{
List<Person> temp = _context.People.Include(i => i.Children).ToList();
output.TagName = "div";
StringBuilder builder = new StringBuilder();
builder.Append("<ul class='treeview mb - 1 pl - 3 pb - 2'>");
foreach (var parent in temp)
{
if (parent.Parent == null)
{
builder.AppendFormat("<li><i class='fas fa-angle-right
rotate'id='rotate'></i><span><i class='far fa-envelope-open ic-w mx-
1'></i>{0}</span>", parent.Name);
if (parent.Children.Count > 0)
{
//Tried some code in here...
//In my possbile wrong opinion, something should've happen in
here so I tried to do something in this part.
}
}
}
builder.Append("</ul>");
output.Content.SetHtmlContent(builder.ToString());
}
In PeopleTreeView()
I have two notes about where did I tried to write some code.
Another Point
If I change my Action method to:
public IActionResult HierarchicalDataStructure()
{
List<Person> temp = _context.People
.Include(i => i.Children)
.Where(x => x.Parent == null).Select(f =>
new Person
{
Id = f.Id,
Name = f.Name,
ParentId = f.ParentId,
Children = f.Children
}).ToList();
return Content(JsonConvert.SerializeObject(new { data = GetAll(temp) },
Formatting.Indented), "application/json");
}
Now I have a proper JSON data without any view.
I would be so glad if someone help me about this situation.. Thank you.