简体   繁体   English

ASP.NET MVC:ActionLink vs bare url

[英]ASP.NET MVC: ActionLink vs bare url

In ASP.NET MVC I see I have handy HTML helpers that I can use to construct form fields and any number of other little things. 在ASP.NET MVC中,我看到我有方便的HTML帮助程序,我可以用它来构建表单字段和任何其他小东西。 But then there's 'ActionLinks'. 但接下来是'ActionLinks'。

Why use an ActionLink instead of just writing the darn url myself in an HTML anchor tag? 为什么要使用ActionLink而不是仅仅在HTML锚标记中编写自己的网址

In other words, why would I use 换句话说,我为什么要使用

<%: Html.ActionLink("Back to List", "QuantityTypes") %>

instead of just using plain ol' HTML and writing: 而不只是使用普通的'HTML和写作:

<a href="/internal/quantitytypes">Back to List</a>

Surely, I must get something extra with the ActionLink. 当然,我必须通过ActionLink获得额外的东西。 I'm just missing it, right? 我只是错过了,对吧?

The action link will build you the proper URL based on the controller , action , areas , params , etc... It generates the URL based on the URL mapping rules defined in the your MVC routing system. 操作链接将根据控制器操作区域参数等为您构建正确的URL ...它根据您的MVC路由系统中定义的URL映射规则生成URL。 It will map params to the correct url as well depending on if it needs to be included in the URL directly or via a querystring param. 它会将params映射到正确的url,具体取决于它是否需要直接或通过查询字符串参数包含在URL中。

Yes you could do it on your own and just type it all out but it builds the URL for you and ensures the URL that is generate is correct. 是的,您可以自己完成,只需输入全部内容,但它会为您构建URL并确保生成的URL正确无误。 It's a helper function... it helps you produce valid links :) 它是一个帮助函数...它可以帮助您生成有效的链接:)

You should read Scott Guthrie's post and pay extra attention to the section " Constructing Outgoing URLs from the Routing System ". 您应该阅读Scott Guthrie的帖子,并特别注意“ 构建路由系统中的传出URL ”部分。 It gives the why and explains other helpers that leverage the routing system. 它给出了原因并解释了利用路由系统的其他帮助程序。

What if you wanted to change the controller name from Internal to External. 如果要将控制器名称从“内部”更改为“外部”,该怎么办? What is going to happen? 会发生什么事? You are going to need to change the href link by hand. 您将需要手动更改href链接。 ActionLink will do automatic routing. ActionLink将执行自动路由。 You don't need to mess with urls. 你不需要弄乱网址。

在裸URL上使用ActionLink的另一个原因是您可能需要向安全资源公开下载链接,该资源只能由应用程序通过身份模拟进行访问。

You get centralized control of your URL's. 您可以集中控制您的URL。 So next time you need to change one for SEO purposes, you don't have to go searching for every place in the application, just switch it in the Global.asax. 因此,下次您需要为SEO目的更改一个时,您不必搜索应用程序中的每个位置,只需在Global.asax中切换它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM