what I’m trying to do is display each item in a list on a razor page:
_layout.cshtml
<div id="LeftSidebar">
<ul>
@foreach (var x in MenuItems.Items)
{
<li><a href="#">@x.ItemName </a></li>
}
</ul>
</div>
menu.cs
public class Menu
{
public string ItemName { get; set; }
public string Alt { get; set; }
public Menu()
{
}
public Menu(string itemName, string alt)
{
ItemName = itemName;
Alt = alt;
}
}
public class MenuItems
{
public static List<Menu> Items = new List<Menu>();
public MenuItems()
{
Items.Add(new Menu
{
Alt = "test item",
ItemName = "item 1",
});
Items.Add(new Menu
{
Alt = "test item",
ItemName = "item 2",
});
}
}
thats what i have so far but it doesn’t display anything?
Thanks
Houlahan
This is because you are never creating an instance of the MenuItems class as your just accessing a static field in the class – therefore the constructor isn’t running and adding the two test items.
Try replacing the MenuItems constructor with a static constructor:
This should ensure the Items field is filled when you access it using MenuItems.Items.