2

I have been trying to learn ASP.NET MVC 3 and things are going well apart from the routing aspect, whatever I try I just can't seem to get them quite right.

I have an ActionLink on the main page:

@Html.ActionLink("Contracts", "List", "Contract", 
                 new { User.Identity.Name, page=1 })

Which is meant to access this method in the ContractController:

public ViewResult List(string user, int page = 1)
{
    //snip
}

My routes are:

 routes.MapRoute(
     null, 
     "Page{page}",
     new { Controller = "Contract", action = "List" }
 );

 routes.MapRoute(
     null,
     "Page{page}",
     new { Controller = "Contract", action = "List", user = "", page = 1 }
 );

 routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
 );

The link now will return a 404 error as it can't find the action 'List' in the controller 'Home', which obviously means it didn't use either of the first routes.

Everything worked before I tried to add parameters to the ActionLink, so basically, what am I doing wrong?

Thanks very much.

2
  • FYI: You do still have a problem because your first and second routes can't be distinguished on incoming requests. All requests (and output links as well) that should be handled by the second one will be done so by the first. Commented Aug 4, 2012 at 8:24
  • Everything seems to work correctly at the moment. I'm not surprised that one of the routes are redundant, I'm still trying to get my head around routing! Would it make a difference if the first two routes were swapped round? Commented Aug 4, 2012 at 9:36

1 Answer 1

1

Alex,

You're doing all the other bits absolutely correctly, however the actionlink has a missing parameter, try this for your actionlink:

@Html.ActionLink("Contracts", "List", "Contract", 
             new { User.Identity.Name, page = 1 }, null)

Adding the null as the final param (htmlAttributes) is all that's missing for you in this scenario (there are 9 overloads for Html.ActionLink, so it's VERY easy to miss the correct implementation).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much, that was exactly the problem! I really need to try and understand the routing system, so far the hardest part of my learning!
no worries alex, another of lifes little mysteries solved. hhmmm, now for the bigger one, the meaning of life!! :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.