While working on my MVC project I found that adding a menu item can be tricky if you don't do it correctly. Instead of
just using a string for the URL, use the RouteValueDictionary class.
Menu Item:
1: public class MenuItem
2: {
3: public string Text { get; set; }
4: public RouteValueDictionary RouteValues { get; set; }
5: }
MenuItemRepository:
1: public class FakeMenuRepository
2: {
3: private IList<MenuItem> items = new List<MenuItem>();
4:
5: public FakeMenuRepository()
6: {
7: AddMenuItem("Home", "Home", "Index", 1);
8: AddMenuItem("Trusts", "Trusts", "List", 1);
9: AddMenuItem("Trusts", "Trusts", "List", 1);
10: }
11:
12: public IList<MenuItem> MenuItems
13: {
14: get
15: {
16: return items;
17: }
18: }
19:
20: public void AddMenuItem(string text, string _controller, string _action, int _page)
21: {
22: MenuItem m = new MenuItem();
23: m.Text = text;
24: m.RouteValues = new RouteValueDictionary(new
25: {
26: controller = _controller,
27: action = _action,
28: page = _page
29: });
30:
31: items.Add(m);
32: }
33: }
Displaying the menu items:
<%foreach(var item in Model){%>
<a href="<%= Url.RouteUrl(item.RouteValues) %>">
<%= item.Text %>
</a>
<%} %>
Url.RouteUrl - Gets or sets the URL pattern for the route. Basically it will create the URL for you and, test that the route you have added is valid against the route table.