我正在尝试在我的控制器中创建一个动态菜单,然后将其渲染到我的视图中。我发现 Controls.Add 正在从我的列表中删除项目,我最终只显示最后一个项目。我如何确保它显示列表中的所有项目以及如何完成显示子元素,因为我正在创建动态菜单?
public string CreateDynamicMenu()
{
HtmlGenericControl navbar = new HtmlGenericControl("nav");
navbar.Attributes.Add("class", "navbar navbar-default");
HtmlGenericControl containerDiv = new HtmlGenericControl("div");
containerDiv.Attributes.Add("class", "container-fluid");
HtmlGenericControl collapseDiv = new HtmlGenericControl("div");
collapseDiv.Attributes.Add("class", "collapse navbar-collapse");
HtmlGenericControl navUl = new HtmlGenericControl("ul");
navUl.Attributes.Add("class", "nav navbar-nav");
HtmlGenericControl dropdownLi = new HtmlGenericControl("li");
dropdownLi.Attributes.Add("class", "dropdown");
HtmlGenericControl mainMenuA = new HtmlGenericControl("a");
var myMenu = menuListForUserG.GetMenus(Global.CurrentProfile.UserID).OrderBy(x => x.MenuOrder).ThenBy(y => y.MenuName);
var navbarmenu = myMenu.Where(x => x.ParentID == null);
foreach (var item in navbarmenu)
{
mainMenuA.InnerText = item.MenuName;
dropdownLi.Controls.Add(mainMenuA);
navUl.Controls.Add(dropdownLi);
}
collapseDiv.Controls.Add(navUl);
containerDiv.Controls.Add(collapseDiv);
navbar.Controls.Add(containerDiv);
StringBuilder htmlStringBuilder = new StringBuilder();
HtmlTextWriter htmlStringWriter = new HtmlTextWriter(new StringWriter(htmlStringBuilder));
navbar.RenderControl(htmlStringWriter);
String output = htmlStringBuilder.ToString();
return output; }