我在RouteConfig中有3条路线:
routes.MapRoute(
name: "ByGroupName",
url: "catalog/{categoryname}/{groupname}",
defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
name: "ByCatName",
url: "catalog/{categoryname}",
defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
name: "ByBrandId",
url: "catalog/brand/{brandId}",
defaults: new { controller = "Catalog", action = "Catalog" }
);
这是我的动作控制器接收参数:
public ActionResult Catalog(
string categoryName = null,
string groupName = null,
int pageNumber = 1,
int orderBy = 5,
int pageSize = 20,
int brandId = 0,
bool bundle = false,
bool outlet = false,
string query_r = null)
{
// ...
}
当我在查看与@Url.RouteUrl("ByBrandId", new {brandId = 5})
的链接时使用,我在操作中输入参数“categoryname”=“brand”而brandId = 0而不是仅使用brandId = 5 ...
当我使用“ByBrandId”routeurl调用"http://localhost:3453/catalog/brand/5"
时,我想在actioncontroller中获得brandId = 5 ...,相当于"http://localhost:3453/catalog/Catalog?brandId=1"
感谢
答案 0 :(得分:4)
您的路由配置错误。如果您传递了网址/Catalog/brand/something
,则始终匹配ByGroupName
路由,而不是预期的ByBrandId
路由。
首先,您应该更正订单。但是,除了可选的组名之外,前两条路线完全相同,因此您可以简化为:
routes.MapRoute(
name: "ByBrandId",
url: "catalog/brand/{brandId}",
defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
name: "ByGroupName",
url: "catalog/{categoryname}/{groupname}",
defaults: new { controller = "Catalog", action = "Catalog", groupname = UrlParameter.Optional }
);
现在,当您使用@Url.RouteUrl("ByBrandId", new {brandId = 5})
时,它应该会为您提供预期的输出/catalog/brand/5
。
有关完整说明,请参阅Why map special routes first before common routes in asp.net mvc。