简体   繁体   中英

ASP.NET wrap an asp:HyperLink in <li>'s, from server-side

I have the next structure for a menu item:

class MenuItem
{
    public string Path, Title;
}

I want to be able to Iterate an object of MenuItem[] , creating a new object of asp:HyperLink on each iteration, and to add it to a <ul> list.

One thing that must happen is that each HyperLink will be inside a <li> tag.

How can I do that?

You can use a repeater. In the aspx:

<asp:Repeater ID="repMenuItems" runat="server">
    <HeaderTemplate>
        <ul>
    </HeaderTemplate>
    <ItemTemplate>
        <li><asp:HyperLink ID="lnkMenuItem" runat="server" Text='<%# Eval("Title") %>' NavigateUrl='<%# Eval("Path")%>'/></li>
    </ItemTemplate>
    <FooterTemplate>
        </ul>
    </FooterTemplate>
</asp:Repeater>

And in the codebehind:

repMenuItems.DataSource = arrMenuItem;  // your MenuItem array
repMenuItems.DataBind();

Additionaly you should change your class code for using Public Properties instead of Public Members, like this:

public class MenuItem 
{ 
    public string Title {get;set;} 
    public string Path {get;set;} 
}

I recommend you to read more about Properties in .NET, a nice feature for object encapsulation http://msdn.microsoft.com/en-us/library/65zdfbdt(v=vs.71).aspx

Hope this helps you

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