那里。我在网页上有一个ul,我在后面的代码中填充了我在树中组织的数据库。我可以从db中获取值并完全列出它们,但是我希望子节点出现在每个父节点下的内部列表中。这是我目前背后的代码
protected void createMenu(TreeView navTree) {
foreach(TreeNode node in navTree.Nodes){
HtmlGenericControl li = new HtmlGenericControl("li");
navMenu.Controls.Add(li);
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "");
anchor.Attributes.Add("class", "toggle");
anchor.Attributes.Add("onClick", "navButton");
anchor.InnerText = node.Text;
li.Controls.Add(anchor);
foreach (TreeNode childNode in node.ChildNodes) {
HtmlGenericControl child_li = new HtmlGenericControl("li");
navMenu.Controls.Add(child_li);
HtmlGenericControl childAnchor = new HtmlGenericControl("a");
childAnchor.Attributes.Add("href", "");
childAnchor.Attributes.Add("onClick", "childButton");
childAnchor.InnerText = childNode.Text;
child_li.Controls.Add(childAnchor);
}
}
}
这是我正在尝试重新创建的html:
<div id="sidebar">
<nav>
<h2>Sites</h2>
<ul>
<li class="toggle"><a href="#">Akron</a></li>
<li class="toggle"><a href="#">Monterey</a></li>
<li class="toggle is-open"><a href="#">Sacramento</a>
<ul class="subnav">
<li><a class="active" href="#"><span class="quantity">5</span> George</a></li>
<li><a href="#"><span class="quantity">7</span> John</a></li>
<li><a href="#"><span class="quantity">18</span> Bob</a></li>
</ul>
</li>
<li class="toggle"><a href="#">Stanislaus</a></li>
</ul>
</nav>
答案 0 :(得分:0)
在内循环中,您需要创建一个子&lt; ul&gt;标签
foreach (TreeNode childNode in node.ChildNodes) {
HtmlGenericControl child_li = new HtmlGenericControl("li");
navMenu.Controls.Add(child_li);
变为
if(node.ChildNodes.Count > 0) {
HtmlGenericControl child_ul = new HtmlGenericControl("ul");
li.Controls.Add(child_ul);
foreach (TreeNode childNode in node.ChildNodes) {
HtmlGenericControl child_li = new HtmlGenericControl("li");
child_ul.Controls.Add(child_li);
等...