tags:

views:

58

answers:

3

I have a UL list in a ASPX page:

<ul id="tabs">
 <li id="tab1"><a href="ztab1.htm">Tab 1</a></li>
 <li id="tab2"><a href="ztab2.htm">Tab 2</a></li>
 <li id="tab3"><a href="ztab3.htm">Tab 3</a></li>
 <li id="tab4"><a href="ztab4.htm">Tab 4</a></li>
 </ul> 

I would like to add list items dynamically from codebehind, including the href entry for each new list item.

How?

+7  A: 

You need to mark your ul as a server side control, then treat the 'new item' as a HtmlGenericControl and insert it into the control collection:

<ul runat="server" id="tabs"> 

To add the item, create a new element and add it:

HtmlGenericControl li = new HtmlGenericControl("li");
ul.Controls.Add(li);

HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "page.htm");
anchor.InnerText = "TabX";

li.Controls.Add(anchor);
GenericTypeTea
A: 

Use asp:bulletedList and your list will be much easier.

<asp:BulletedList id="blTabs" 
  BulletStyle="Disc"
  DisplayMode="LinkButton" 
  runat="server">
    <asp:ListItem Value="ztab1.htm">tab1</asp:ListItem>
    <asp:ListItem Value="ztab2.htm">tab2</asp:ListItem>
    <asp:ListItem Value="ztab3.htm">tab3</asp:ListItem>
</asp:BulletedList>

Code Behind:

    ListItem li = new ListItem();
    li.Value = "*.html";  //html goes here i.e.  xtab1.html
    li.Text = "New Text";  //text name goes i.e. here tab1
    blTabs.Items.Add(li);
Nix
A: 

This result is the same as GenericTypeTea's, but the difference is the HTML is 'written' in the code behind and injected into the page.

In your markup:

<asp:Literal id="litMarkup" runat="server" />

In your code behind:

List<string> locations  // however this initialized 

StringBuilder sb = new StringBuilder();

sb.Append("<ul id=\"tabs\">");

for (int i = 0; i < locations.Count; i++)
{
   sb.Append("<li id=\"tab" + i.ToString() + "\"><a href=\"" + locations[i] + "\">Tab " + i.ToString() + "</a></li>");
}

sb.Append("</ul>");

litMarkup.Text = sb.ToString();
Scott Lance
Awesome how I'm marked down on a perfectly workable and valid answer without any explanation.
Scott Lance
@scott - It happens mate, don't take it personally. Some users are too cowardly to give an explanation for their downvote. I didn't give the downvote but I'm guessing you got it because this is an ill-advised way of doing it. Not because it doesn't give the same output, but because it's an absolute maintenance nightmare, a lot more code and quite unreadable. We banned this sort of code from our projects a long time ago. The `TagHelper` in ASP.Net MVC is a nice way of doing something similar to your answer though.
GenericTypeTea
@GenericTypeTea - Thanks for your explanation, I wasn't aware using a literal was considered a bad practice
Scott Lance