0

这是我的RouteConfig.cs

routes.MapRoute(null,
                        "{controller}/Page{page}",
                        new {controller = "Product", action = "Index", category = (string) null},
                        new {page = @"\d+"}
            );

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

        routes.MapRoute(null,
                        "{controller}/{category}/Page{page}",
                        new {controller = "Product", action = "Index"},
                        new {page = @"\d+"}
            );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

这是生成url的代码:

@Html.ActionLink("View Cart", "Index", "ShoppingCart", null, new { @class = "btn btn-orange" })

例如,当我导航到 、 、 时,它Product/Page2运行Product/Laptop良好Product/Laptop/Page2。问题是,只要我当前的 URL 包含Page段,它就会尝试重用该段来生成传出 URL。所以,如果我在Product/Page2上面生成的 URL 将是ShoppingCart/Page2. 我不知道如何避免这种情况。

请帮我。太感谢了。

编辑!!!

我找到了一种解决方法。ActionLink我没有使用,而是这样使用RouteLink

@Html.RouteLink("View Cart", "Default", new { controller = "ShoppingCart", action = "Index" }, new { @class = "btn btn-orange" })

但我仍然想使用ActionLink,所以请帮助我。

编辑!!!

当我生成指向ShoppingCart/Checkout. 它仍然需要我在控制器中Index采取行动。ShoppingCart

4

2 回答 2

1

创建特定于 ShoppingCart 的新路线模式,并将其放置在 TOP使其成为第一条路线。

    routes.MapRoute(null,
                    "ShoppingCart/{action}",
                    new {controller = "Product"});
        );

作为一项规则,所有特定的路线都应该排在第一位。

于 2014-01-17T10:33:54.670 回答
0

这是因为路由系统在尝试匹配路由时尝试评估段变量值的方式。

因此,当使用以下参数调用渲染链接时:

@Html.ActionLink("View Cart", "Index", "ShoppingCart", null, new { @class = "btn btn-orange" })

使用模板评估路线时的框架

{controller}/Page{page}

将解析controller段变量,ShoppingCart但是当它无法找到page段变量的值(通过方法调用中的任何参数)时,它将尝试从 ViewContext 中的 RouteData 对象解析该值。由于您已导航到,因此路由值字典中Product/Page2的当前值为。page2

ViewContext.RouteData.Values["page"]您可以通过查看渲染该视图时的值来检查这一点。

于 2015-03-24T09:25:08.080 回答