为什么 RouteLink 会生成友好的 URL,而 ActionLink 不会?
我有一个关于 RouteLink 与 ActionLink 的问题。
考虑以下路由
routes.MapRoute("Routename1",
"{someEnum}/SpecificAction/{id}/{stringId}",
new { controller = "MyController", id = (int?)null, stringId= (string)null, action = "SpecificAction" },
new { someEnum= "(EnumVal1|EnumVal2)" }
);
奇怪的 {someEnum} 部分是因为我对形成 url 的典型控制器部分的枚举的所有值使用通用控制器。例如,/EnumVal1/Action/ 和 /EnumVal2/Action/ 使用相同的控制器。然而,这不是问题的一部分。
考虑以下两种链接方式:
<%=Html.RouteLink("Click me","Routename1", new { id = 32, stringId = "Yatzy" })%>
<%=Html.ActionLink("Click me", "SpecificAction", "EnumVal1", new { id = 32, stringId = "Yatsy" }, null)%>
RouteLink 生成正确的 url,即 /EnumVal1/SpecificAction/32/Yatzy
ActionLink 生成类似于 /EnumVal1/SpecificAction/32?stringId=Yatzy 的 url
这是为什么?请有人向我解释一下。
I have a question regarding RouteLink vs. ActionLink.
Consider the following route
routes.MapRoute("Routename1",
"{someEnum}/SpecificAction/{id}/{stringId}",
new { controller = "MyController", id = (int?)null, stringId= (string)null, action = "SpecificAction" },
new { someEnum= "(EnumVal1|EnumVal2)" }
);
The weird {someEnum} part is because I use a general controller for all values of an enum that form the typical controller part of a url. For instance, /EnumVal1/Action/ and /EnumVal2/Action/ use the same controller. That's not part of the problem, however.
Consider the following two ways of linking:
<%=Html.RouteLink("Click me","Routename1", new { id = 32, stringId = "Yatzy" })%>
<%=Html.ActionLink("Click me", "SpecificAction", "EnumVal1", new { id = 32, stringId = "Yatsy" }, null)%>
The RouteLink generates the correct url, which would be /EnumVal1/SpecificAction/32/Yatzy
The ActionLink generates an url that looks like /EnumVal1/SpecificAction/32?stringId=Yatzy
Why is this? Could someone explain this to me, please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
RouteLink
只能使用您指定的一条路线。ActionLink
将使用第一个匹配的路由,无论它是否是您想要的路由。您的两个示例可能匹配不同的路线。Phil Haack 的路由调试器将有助于澄清这一点。
RouteLink
can only ever use the one route you specify.ActionLink
will use the first matching route, whether it's the one you intended or not. Your two examples are probably matching different routes.Phil Haack's routing debugger would help clarify this.