1

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 ?

2
  • In your optional parameters, you have pays instead of country. I'm not sure if that makes a difference. Commented Mar 28, 2013 at 20:03
  • I'm not too good with regex, but I believe you are adding a constraint saying to make sure that the country is either france or belgium. So when you don't provide it, it doesn't set the value of the country. Commented Mar 28, 2013 at 20:04

1 Answer 1

4

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.

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

1 Comment

"Optional parameters must follow any required parameters." I didn't know about that rule, I guess that answer the question, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.