1

I have a question regarding construct HTML tags on back-end code (c#) in my ASP.NET application.

Let say I have a DataTable as below:

enter image description here

I would like to dynamically convert (using multiple foreach and if else condition) the DataTable into a form of ul and li as below:

enter image description here

Finally my expected output:

enter image description here

what is the best practice of achieve this? Please help.

Thank you in advanced.

Updated: I've found another alternative solution from this post How do I display non-normalized data in a hierarchical structure?

2
  • It depends on how that table is being generated...How is it being generated, or is that what the data in the database looks like? Commented Mar 17, 2012 at 19:45
  • the table is not fixed, the table above is how the data going to store Commented Mar 18, 2012 at 2:58

1 Answer 1

3

You essentially have a hierarchy of people (parent) that contain other people (children and grand children), so you could use a recursive function to traverse the children of a Person object. Something like this:

public class Person
{
    public IEnumerable<Person> Children { get; set; }
    public string Name { get; set; }
    public string Link { get; set; }
}

public class PeopleHtmlGenerator
{
    public string GetPeopleHtml(IEnumerable<Person> people)
    {
        return string.Format("<div>{0}</div>", GetChildren(people));
    }

    private string GetChildren(IEnumerable<Person> people)
    {
        StringBuilder result = new StringBuilder();
        result.AppendLine("<ul>");
        foreach (var person in people)
        {
            result.AppendLine(string.Format("<li><a href=\"{0}\">{1}</a></li>", person.Link, person.Name));
            result.AppendLine(GetChildren(person.Children));
        }
        result.AppendLine("</ul>");
        return result.ToString();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That is a very elegant solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.