简体   繁体   中英

ASP.net MVC 4 Routing and optional parameters unexpected result

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM