我有一个带有索引操作的清单控制器,该操作采用可选的类别参数...
public ActionResult Index(string category) { ... }
我在global.asax中有标准的默认路由......
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
如果我打电话......
@Html.ActionLink("Show All Listings", "Index", "Listings")
...从视图中(甚至是指定类别的相同操作的视图)我得到一个指向“/ Listings”的链接。
如果我打电话......
@Html.ActionLink("Show Listings for Category A", "Index", "Listings", new { category = "CategoryA" }, null)
...我收到了“/ Listings?category = CategoryA”的链接。到目前为止一切都很好。
所以我想要实现的是在指定类别时创建自定义路由。为此,我在上述路线之前添加了一条到global.asax的自定义路线,如下所示:
routes.MapRoute(
"ListingCategories",
"listings/category/{category}",
new { controller = "Listings", action = "Index" }
);
现在,如果我打电话......
@Html.ActionLink("Show Listings for Category A", "Index", "Listings", new { category = "CategoryA" }, null)
...我得到一个很好的链接“/ Listings / Category / CategoryA”
但这是问题所在。如果我打电话......
@Html.ActionLink("Show All Listings", "Index", "Listings")
...从类别=“CategoryA”的上述操作的视图中,生成的链接是“/ Listings / Category / CategoryA”而不仅仅是“/ Listings”。但是,当我从任何其他视图进行相同的调用时,链接生成为“/ Listings”。
我试过打电话......
@Html.ActionLink("Show All Listings", "Index", "Listings", new { category = "" }, null)
...当从具有category =“CategoryA”的操作的视图调用时,它仍然生成“/ Listings / Category / CategoryA”链接。但是,如果我将category设置为任何非空字符串,那么它会生成指向正确类别的链接(无论我指定什么)。
这是预期的行为吗?
答案 0 :(得分:1)
修改您的路线,以便category
是可选的
routes.MapRoute(
"ListingCategories",
"listings/category/{category}",
new { controller = "Listings", action = "Index", category = UrlParameter.Optional }
);
您之前的路线会生成所需的类别,因此ActionLink
与该路线不匹配,而是匹配另一条路线,例如默认路线。