开发者

MVC omit optional page parameter

开发者 https://www.devze.com 2023-01-04 03:55 出处:网络
I have the following URL in mind: /restaurants/italian/miami.html /restaurants/italian/miami-p2.html Using these routes

I have the following URL in mind:

/restaurants/italian/miami.html
/restaurants/italian/miami-p2.html

Using these routes

routes.MapRoute(null, "{category}/{branch}/{city}-p{page}.html",
                new { controller = "Branch", action = "Index" });
routes.MapRoute(null, "{category}/{branch}/{city}.html",
                new { controller = "Branch", action = "Index", page = 1 });

Now for m开发者_JAVA百科y question, i want to make "-p{page}" portion of the url optional, not just the {page} parameter. That way i can use a single route and also use it to map outbound urls with Url.RouteUrl(RouteValueDictionary) (which then auto removes the page portion if the page parameter in the dictionary is 1).


I am not sure I understand well what you would like, still somehow I think that using some regular expression constraint might solve your problem. Maybe somehow like this:

routes.MapRoute(null, "{category}/{branch}/{citywithp}{page}.html",
            new { controller = "Branch", action = "Index" },
            new {citywithp = @"p-\d+$" } );


In order to achieve this i needed 3 routes:

routes.MapRoute(null, "{category}/{branch}/{city}.html",
                new { controller = "Branch", action = "Index" },
                new { page = "1" });

routes.MapRoute(null, "{category}/{branch}/{city}-p{page}.html",
                new { controller = "Branch", action = "Index" });

routes.MapRoute(null, "{category}/{branch}/{city}.html",
                new { controller = "Branch", action = "Index", page = 1 });

This way i can map all the urls inbound with the second and third route and outbound with the first and second.

0

精彩评论

暂无评论...
验证码 换一张
取 消