I´m trying to create a recursive method to create a menu. The menu I want to achieve displays the childrens children and so on. I´ve debugged the code and it goes all the way down to the "youngest child".
public string GetMenu(Node currentPage)
{
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
foreach (var item in currentPage.ChildrenAsList)
{
writer.RenderBeginTag(HtmlTextWriterTag.Li);
writer.AddAttribute(HtmlTextWriterAttribute.Href, item.Url);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write(item.Name);
if (item.ChildrenAsList.Any())
{
writer.RenderBeginTag(HtmlTextWriterTag.Ul);
GetMenu(new Node(item.Id));
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.RenderEndTag();
}
}
return stringWriter.ToString();
}
This method give the output:
<ul class="nav nav-sidebar">
<li>
<a href="/artikelsida001/">Artikelsida001
<ul>
</ul>
</a></li>
<li><a href="/patrikartikelsida/">PatrikArtikelsida
<ul>
</ul>
</a></li>
<li><a href="/en-testsida/">En testsida</a></li>
</ul>
Each time you call GetMenu
, you're creating a new StringWriter
- but you're ignoring the return value from your recursive calls. The simplest fix would probably be to change it to:
public string GetMenu(Node currentPage)
{
var stringWriter = new StringWriter();
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
RenderMenu(currentPage, writer);
}
return stringWriter.ToString();
}
private void RenderMenu(Node node, HtmlTextWriter writer)
{
// Mostly copied from the code in the question...
foreach (var item in currentPage.ChildrenAsList)
{
writer.RenderBeginTag(HtmlTextWriterTag.Li);
writer.AddAttribute(HtmlTextWriterAttribute.Href, item.Url);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write(item.Name);
if (item.ChildrenAsList.Any())
{
writer.RenderBeginTag(HtmlTextWriterTag.Ul);
// Note the change here
RenderMenu(new Node(item.Id), writer));
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.RenderEndTag();
}
}
Note how the recursion now calls RenderMenu
with the same writer.
See more on this question at Stackoverflow