【发布时间】:2014-07-25 13:55:49
【问题描述】:
在上面的项目(MVC 5)中,我遇到了 Html.ActionLink 问题,似乎没有从当前所在的页面中清除路由参数。
在一页上对 Html.ActionLink 的完全相同的调用会产生不同的结果,具体取决于您对路线的“深度”。下面是我的示例控制器
// GET: Sample
public ActionResult Index()
{
return View("Index");
}
[Route("sample/example/{categoryid}")]
public ActionResult Example(int categoryID)
{
ViewBag.categoryID = categoryID;
return View("Example");
}
[Route("sample/example/{parentcategoryid:int}/{categorydepth:int}")]
public ActionResult Example(int parentcategoryID, int categorydepth)
{
ViewBag.parentcategoryID = parentcategoryID;
ViewBag.categorydepth = categorydepth;
return View("Example");
}
下面是来自样本/索引视图的 sn-p
@Html.ActionLink("Link", "Example", new { controller = "Sample", categoryid = 100 }, null)
这会产生以下 HTML:http://localhost:2762/sample/example/100
下面是来自示例/示例视图的 sn-p
@Html.ActionLink("Link", "Example", new { controller = "Sample", categoryid = 100 }, null)
<br />
@Html.ActionLink("Deeper Link", "Example", new { controller="Sample", parentcategoryid=9999, categorydepth=2})
第一次点击索引视图中的链接时...“链接”Html 是相同的:http://localhost:2762/sample/example/100
如果您单击“更深层次的链接”,您会再次看到相同的视图...但是“链接”Html 现在是:http://localhost:2762/sample/example/9999/2?categoryid=100,它显然没有到达您想要的位置。
这基本上是用于浏览产品类别的面包屑场景。
有什么想法可以解决这个问题吗?
【问题讨论】:
-
我知道这可能看起来很奇怪,但是如果您将您的方法与更长的路线放在另一个之前会发生什么?问题在于,因为它们使用相同的前缀路由,如果使用 categoryid 的路由集合中的第一个,则始终会被选中。
-
无变化...点击“深层链接”后参数仍然不正确
-
有趣的是......如果我交换订单值(根据已删除答案中的建议),问题也会交换。当您第一次访问该页面时,错误链接位于 Deeper Link 上。 O_o
-
我不知道为什么我之前没有提到这一点,但是将方法名称更改为唯一肯定会解决您的问题。
-
更改方法名称(但离开路由)导致“链接” url 为 localhost:2762/Sample/Example?categoryid=100 如此令人沮丧。我试图避免路线名称的混乱。短期解决方案可能是制作旧式链接……但如果路线发生变化,这将无济于事。
标签: c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing