Adding menu items with valid routes to ASP.Net MVC

by Jacobus Meintjes July 14, 2009 09:54

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.

Tags:

ASP.Net MVC

Comments are closed

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen | Modified by Mooglegiant

About Me

Jacobus Meintjes
 
C# developer working with ASP.Net and/or Windows Forms.
Email Me

Cumulus

This will be shown to users with no Flash or Javascript.

Widget Twitter not found.

Root element is missing.X