代码之家  ›  专栏  ›  技术社区  ›  Fabian

MVC省略可选页参数

  •  1
  • Fabian  · 技术社区  · 15 年前

    我想到了以下网址:

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

    使用这些路线

    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 });
    

    现在,对于我的问题,我想让URL的“-p page”部分可选,而不仅仅是page参数。这样我就可以使用单个路由,也可以使用它来映射出站URL Url.RouteUrl(RouteValueDictionary) (如果字典中的page参数为1,则自动删除page部分)。

    2 回复  |  直到 15 年前
        1
  •  1
  •   apolka    15 年前

    我不确定我很清楚你想要什么,不过我还是觉得用一些 regular expression constraint 可能会解决你的问题。也许是这样:

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

    为了实现这一目标,我需要3条路线:

    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 });
    

    通过这种方式,我可以将所有入站URL映射到第二和第三个路由,并将出站URL映射到第一和第二个路由。

    推荐文章