Asp.net mvc 4 由于MVC4中的段变量重用,生成错误的传出url
这是我的Asp.net mvc 4 由于MVC4中的段变量重用,生成错误的传出url,asp.net-mvc-4,asp.net-mvc-routing,Asp.net Mvc 4,Asp.net Mvc Routing,这是我的RouteConfig.cs routes.MapRoute(null, "{controller}/Page{page}", new {controller = "Product", action = "Index", category = (string) null}, new {page = @"\d+"} );
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包含页面
段时,它都会尝试重用该段来生成传出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
的链接时,解决方法不起作用。在ShoppingCart
控制器中,我仍然需要索引操作。创建一个特定于ShoppingCart的新路线模式,并通过将其置于顶部,使其成为第一条路线
routes.MapRoute(null,
"ShoppingCart/{action}",
new {controller = "Product"});
);
作为一项规则,所有特定的路由都应该放在第一位。这是因为路由系统在试图与路由匹配时试图评估段变量值的方式
因此,当使用以下参数调用呈现链接时:
@Html.ActionLink(“查看购物车”、“索引”、“购物车”,空,新{@class=“btn btn orange”})
使用模板评估路由时的框架
{controller}/Page{Page}
将控制器
段变量解析为ShoppingCart
,但是当它无法找到页面
段变量的值时(通过方法调用中的任何参数),它将尝试从ViewContext中的RoutedData对象解析该值。由于您已导航到Product/Page2
,因此路由值字典中page
的当前值为2
在呈现该视图时,您可以通过查看ViewContext.routedData.Values[“page”]
的值来检查此情况。对于购物车链接,您的目标路径是哪条路径?最后一条,只是普通模式,控制器/操作。但它与第二条路径本身相匹配。你需要用更多的约束来缩小第二个映射,或者重新排列映射,看看是否有帮助。我现在该怎么做?第二个是产品类别。当我将所有{controller}
更改为产品
时,一切都能正常工作。这就是解决方案吗?如果该路线只针对产品
控制器,那么这就是解决方案。