1

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?

Novak
  • 2,760
  • 9
  • 42
  • 63

1 Answers1

3

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

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
  • Can do the same thing in a Listview if you need the more robust functionality of the Listview. Though if you dont then the repeater is lighterweight – Chad Dec 28 '12 at 19:34
  • @Agustin Meriles, thanks for your solution. Testing it gave me an Error: "DataBinding: 'NAMESPACE.MenuItem' does not contain a property with the name 'Title'. – Novak Dec 28 '12 at 20:47
  • I Believe that the problem is that Title is not a Property, but a Member. You should try using Properties insted of Members. Change you class code like this: `public class MenuItem { public string Title {get;set;} public string Path {get;set;} }` – Agustin Meriles Dec 28 '12 at 22:11