Controls.Add从列表中删除以前的项目

时间:2016-02-11 18:48:50

标签: c# asp.net-mvc html-generation htmlgenericcontrol

我正在尝试在我的控制器中创建一个动态菜单,然后我将渲染到我的视图中。我发现是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; }

1 个答案:

答案 0 :(得分:2)

问题是您在循环中反复添加dropdownLimainMenuA的相同实例。我想Control.Add不会在列表中添加重复项,因此控件只能有效地添加一次。在循环的最后一次运行中,您将文本更改为最后一项的文本。

为了解决这个问题,您需要按如下方式创建新实例:

foreach (var item in navbarmenu)
{
    // Move the following lines from outside the loop inside
    HtmlGenericControl dropdownLi = new HtmlGenericControl("li");
    dropdownLi.Attributes.Add("class", "dropdown");
    HtmlGenericControl mainMenuA = new HtmlGenericControl("a");    
    mainMenuA.InnerText = item.MenuName;
    dropdownLi.Controls.Add(mainMenuA);
    navUl.Controls.Add(dropdownLi);                    
}