Terry
Terry

Reputation: 14219

MVC3 routing confusion

I want to be able to access the following through one route constraint declaration:

/picks                        
/picks/{teamID}/{week}        
/picks/save/{teamID}/{week}   

This does not work for the second request: /picks/{teamID}/{week}

routes.MapRoute(
  "picks",
  "picks/{action}/{teamID}/{week}",
  new { controller = "Picks", 
        action = "Index", 
        teamID = UrlParameter.Optional, 
        week = UrlParameter.Optional });

It seems to me the action should be defaulted to Index since I don't supply one, but I'm assuming it's actually trying to find the action {teamID} (which is a number).

How do I make this constraint handle all 3 scenarios?

Upvotes: 3

Views: 85

Answers (2)

Eonasdan
Eonasdan

Reputation: 7765

Check out Phill Haack route debugger.

You can also add constraints so that the teamId will only be picked up if it's a number

routes.MapRoute(
  "picks",
  "picks/{action}/{teamID}/{week}",
  new
  {
      controller = "Picks",
      action = "Index",
      teamID = UrlParameter.Optional,
      week = UrlParameter.Optional
  },
  new { teamID = @"\d+" });

Upvotes: 1

Ricardo Souza
Ricardo Souza

Reputation: 16468

You just have to omit the action from the rout string for the first route:

routes.MapRoute( 
    "picks", 
    "picks/{teamID}/{week}", 
    new { controller = "Picks",  
            action = "Index",  
            teamID = UrlParameter.Optional,  
            week = UrlParameter.Optional }); 

Remember to place more specific routes on top of more generic ones.

Eg:

"picks/{teamID}/{week}"
"picks/{action}/{teamID}/{week}"
"{controller}/{action}/{id}"

The routes are tryed in the order they are added.

Upvotes: 1

Related Questions