当我有一个路由需要多个参数时,我在使用Html.ActionLink时遇到了问题。例如,假设我的Global.asax文件中定义了以下路由:
routes.MapRoute(
"Default", // Route name
"{controller}.mvc/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"Tagging",
"{controller}.mvc/{action}/{tags}",
new { controller = "Products", action = "Index", tags = "" }
);
routes.MapRoute(
"SlugsAfterId",
"{controller}.mvc/{action}/{id}/{slug}",
new { controller = "Products", action = "Browse", id = "", slug = "" }
);前两个路由正常工作,但当我尝试使用以下命令创建指向第三个路由的操作链接时:
<%= Html.ActionLink(Html.Encode(product.Name), "Details", new { id = product.ProductId, slug = Html.Encode(product.Name) }) %>我最终得到了一个类似site-root/Details/1?slug=url-slug的网址,而我希望这个网址更像site-root/Details/1/url-slug
有没有人能看到我哪里出了问题?
发布于 2009-04-09 13:36:26
它使用的是第一条完全满足的路由。尝试将您的SlugsAfterId路由放在Default路由之上。
它基本上是这样的:“检查默认值。有动作吗?是的。有id吗?是的。使用这个id并去掉querystring中的任何其他参数。”
注意,当您为slug参数提供默认值时,这样做将使您的Default路由变得冗余。
发布于 2009-04-09 13:39:46
Garry (上图)是正确的。你可以使用Haack先生的MVC路由调试器。它可以通过显示命中哪些路由以及何时命中来帮助解决路由问题。
这是Blog Post。这是Zip File。
发布于 2009-06-22 21:17:59
您可以向包含"id“的路由添加一个约束,因为它可能只接受一个数字。这样,只有当"id“是数字时,第一个路由才会匹配,然后它将为所有其他值生成第二个路由。然后将包含{slug}的那个放在顶部,一切都应该正常工作。
routes.MapRoute(
"SlugsAfterId",
"{controller}.mvc/{action}/{id}/{slug}",
new { controller = "Products", action = "Browse", id = "", slug = "" },
new { id = @"\d+" }
);
routes.MapRoute(
"Default", // Route name
"{controller}.mvc/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new { id = @"\d+" }
);
routes.MapRoute(
"Tagging",
"{controller}.mvc/{action}/{tags}",
new { controller = "Products", action = "Index", tags = "" }
);https://stackoverflow.com/questions/734249
复制相似问题