Reputation: 427
Here is my route, the only required param is the controller
routes.MapRoute(
"countryoptional/controller",
"{country}/{controller}/{pagelabel}/{page}",
new { action = "index", country = UrlParameter.Optional, pagelabel = UrlParameter.Optional, page = UrlParameter.Optional },
new
{
pays = @"$|^(france|belgium)$",
controller = @"^(car|boat)$",
pagelabel = @"^$|page",
page = @"^$|\d{1,6}"
}
);
I'm expecting the following URLS to work with :
/car/
/car/page/2
/france/car
/france/car/page/2
It kind of works :
Url.Action("index", "car", new { country= "france", pagelabel = "page", page = 2} )
Will produce : /france/car/page/2
BUT
If I want an url without a country the view action respond but a constructor like
Url.Action("index", "car", new { pagelabel = "page", page = 2} )
will produces this link : //car/page/2
I get this double slash "//car" so it breaks the link of course.
I suspect the fact it does not like the possibility of the {country} parameter preceding controller optional in the {country}/{controller}/... url definition I don't want to complicate my route config and having another route declaration There must be a way, what I'm I doing wrong ?
Upvotes: 1
Views: 2576
Reputation: 239250
Optional parameters must follow any required parameters. There's no way around this that I know of. The same limitation applies everywhere else (your method definitions, etc.).
Just repeat the route and have one with a required country and one without any country. MVC will work out which one to use.
Upvotes: 4