ASP.NET - 建筑HTML标签动态 [英] ASP.NET - Construct HTML Tags Dynamically
问题描述
我有一个关于我的ASP.NET应用程序构建后端code HTML标签(C#)的问题。
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:
我想转换成动态(使用多个的foreach,如果其他条件)DataTable中为UL和下面李形式:
I would like to dynamically convert (using multiple foreach and if else condition) the DataTable into a form of ul and li as below:
最后我期望的输出:
什么是实现这一目标的最佳做法?
请帮助。
what is the best practice of achieve this? Please help.
感谢您先进的。
更新:
我发现从这个帖子<一个又一个替代解决方案href=\"http://stackoverflow.com/questions/2783337/how-do-i-display-non-normalized-data-in-a-hierarchical-structure\">How做我显示层次结构中的非规范化的数据?
推荐答案
您实际上有包含其他人(孩子和孙子女)人(父母)的层次结构,所以你可以使用递归函数来遍历的孩子一个人
对象。事情是这样的:
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();
}
}
这篇关于ASP.NET - 建筑HTML标签动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!