What's the difference between RouteLink and ActionLink in ASP.NET MVC?

I think that the title pretty much sums it up:

What's the difference between RouteLink() and ActionLink() in ASP.NET MVC?

i.e. when do you use Html.RouteLink() and when do you use Html.ActionLink() in your View?

40874 次浏览

RouteLink takes the name of a route, so if your route names are reliable and fairly unique then this will be the same even if the action name to be used changes. ActionLink links to a specific action of a specific controller instead. I use both in my views, depending on what kind of link I'm after!

Action 和 Routes 不一定是1:1的关系。

ActionLink 将使用第一个按操作名称匹配的路由生成到达操作的 URL。

RouteLink 将生成指向特定路由的 URL,该路由由名称或路由值确定。

实际上,这两个方法的输出是相同的,但它们的生成方式略有不同:

Html.ActionLink() makes it easy to generate ActionLinks fast, and will give you basic control over what is rendered. If you don't have too many routes, or don't need to give too much or too specific information, this will do the work just fine.

Html.RouteLink()方法使用的参数略有不同,因此可以更详细地控制处理事情的方式。我倾向于在场景稍微复杂一点或者有更详细的路线结构时使用这种方法。
一个例子是最近的一个项目,我(为了灵活性)有几个不同的路线,它们都非常简单,而不是一个复杂的路线,因为它可以提供大量的信息。因此,我最终为同一个 Controller 指定了四到五个路由,所有这些路由都指定了缺省操作。我主要使用 RouteLink版本,因为当我指定路由名称时,会自动输入默认参数。

随心所欲地使用它们,并在它们对您的项目有意义时使用它们。这两者实际上都没有什么好处或坏处(这是其他人所无法比拟的... ...)。

除了这里给出的其他答案之外,RouteLink 稍微快一点,而且永远不会匹配错误的路由,因为您更改了路由表。