简体   繁体   中英

Add <li> to <ul> tag from code behind C# ASP NET

well how the title says, how can I add various <li> tags to a <ul> tag from code behind. I tried this Add to List from codebehind C# Asp.net this is my example code.

ASP

<body>
<form id="form1" runat="server">
<div>
    <ul id="menu" runat="server"> </ul>

</div>
</form>

And code behind.

        protected void Page_Load(object sender, EventArgs e)
    {
        CreateMenu();


    }

    protected void CreateMenu()
    {
        HtmlGenericControl li = new HtmlGenericControl("li");
        menu.Controls.Add(li);

        HtmlGenericControl anchor = new HtmlGenericControl("a");
        anchor.Attributes.Add("href", "login.aspx");
        anchor.InnerText = "login";



        li.Controls.Add(anchor);
    }

Well it works perfectly but maybe this gonna be a dumb question, how can I add more than one element to the <ul> tag? I need to create an new object for each item (I think this is wrong) or exist a better way to do this?

I searched but any example satisfies my doubt, sorry if you think is a repeated question.

If your datas(menu items) are not coming from a source(something like database), you need to repeat the same process over and over again unfortunately. Or you can create a function which is taking 2 parameters, text and link. This way you can do this job with 1 line.

  private void AddMenuItem(string text, string link)
    {
        HtmlGenericControl li = new HtmlGenericControl("li");
        menu.Controls.Add(li);

        HtmlGenericControl anchor = new HtmlGenericControl("a");
        anchor.Attributes.Add("href", link);
        anchor.InnerText = text;



        li.Controls.Add(anchor);
    }

    AddMenuItem("text","link");
    AddMenuItem("text2","link2");
    AddMenuItem("text3","link3");

You can improve this for your specific needs.

You can use ListView. It's easier format. I also found a good tutorial about it ( http://weblogs.asp.net/scottgu/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui )

<asp:ListView ID="ListView1" runat="server">
    <LayoutTemplate>
        <ul>
            <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
        </ul>
    </LayoutTemplate>
    <ItemTemplate>
        <li>
            <div>
                <p class="name"><%# Eval("author") %></p>
                <p class="date"><%# Eval("insertDate") %></p>
            </div>
            <p class="comment"><span class="<%# Eval("icon") %>"></span><%# HttpUtility.HtmlEncode(Eval("comment")) %></p>
        </li>
    </ItemTemplate>
</asp:ListView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM