views:

373

answers:

3

Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.

A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?

routes.MapRoute("UserItems", "User/{UserID}/Items", 
                      new {controller = "User", action = "Items"});

And on my aspx page

Html.ActionLink("Items", "UserItems", new { UserID = 1 })
+1  A: 

Can you post more information? What URL is the aspx page generating in the link? It could be because of the order of your routes definition. I think you need your route to be declared before the default route.

Ricky
+4  A: 

Going by the MVC Preview 4 code I have in front of me the overload for Html.ActionLink() you are using is this one:

public string ActionLink(string linkText, string actionName, object values);

Note how the second parameter is the actionName not the routeName.

As such, try:

Html.ActionLink("Items", "Items", new { UserID = 1 })

Alternatively, try:

<a href="<%=Url.RouteUrl("UserItems", new { UserId = 1 })%>">Items</a>
Graphain
A: 

Firstly start with looking at what URL it generates and checking it with Phil Haack's route debug library. It will clear lots of things up.

If you're having a bunch of routes you might want to consider naming your routes and using named routing. It will make your intent more clear when you re-visit your code and it can potentially improve parsing speed.

Furthermore (and this is purely a personal opinion) I like to generate my links somewhere at the start of the page in strings and then put those strings in my HTML. It's a tiny overhead but makes the code much more readable in my opinion. Furthermore if you have or repeated links, you have to generate them only once.

I prefer to put

<% string action = Url.RouteUrl("NamedRoute", new 
    { controller="User",
      action="Items",
      UserID=1});%>

and later on write

<a href="<%=action%>">link</a>
borisCallens