MVC - 为什么要使用ActionLink的而不是硬编码的链接? [英] MVC - why use ActionLink instead of hard coding the link?

查看:349
本文介绍了MVC - 为什么要使用ActionLink的而不是硬编码的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

微软MVC,剃须刀时,Visual Studio 2013

我可以创建使用这两种2种方法的链接。是否有使用Html.ActionLink方法,因为我看不到任何什么好处?

 < A HREF =/评论/ MyReviews>我的评论和LT; / A>@ Html.ActionLink(LINKTEXT:=我的评论,controllerName:=评论,actionName:=MyReviews)

谢谢,
约翰·


解决方案

这是用有用 Url.Action()的URL生成和 Html.ActionLink()来产生锚标签,因为这将确保产生正确的相对的网址操作控制器名称。

在当应用程序在内蒙古目录托管我们的 CSS 样式表 JS 文件不加载因错误的URL。

考虑情况下,您正在使用的锚标记与你第一种方法在页面和视图是嵌套子目录例如查看 - >首页 - >局部模板 - > _Index.cshtml

现在,如果你写锚标记是这样的:

 < A HREF =/关于/​​索引>关于< / A>

现在我们是在说去一个目录当时关于控制器和索引操作,但在当前情况下正确的URL将是:

 < A HREF =../关于/索引>关于< / A>

和写作以下将确保网址锚标记生成正确的:

 < A HREF =@ Url.Action(指数,关于)>关于< / A>

  Html.ActionLink(LINKTEXT:=关于,controllerName:=关于,actionName:=索引)

使用普通硬盘codeD URL导致问题想在这个<一个href=\"http://stackoverflow.com/questions/23192654/mvc-controller-function-failed-calling-from-ajax\">SO帖子。

OP面临的问题Ajax调用没有得到,因为错误的URL的作用,并使用 @ Url.Action()帮助解决了这个问题,因为它可以确保URL生成正确的。

您也应该阅读这个内容丰富的文章,以让更加清楚的认识

Microsoft MVC, Razor, Visual Studio 2013

I can create a link using either of these 2 methods. Is there any benefits in using the Html.ActionLink method, as I cannot see any ?

<a href="/Review/MyReviews">My Reviews</a>

@Html.ActionLink(linkText:="My Reviews", controllerName:="Review", actionName:="MyReviews")

thanks, John

解决方案

Yes. It is useful to use Url.Action() for url generation and Html.ActionLink() to generate anchor tags as it will make sure to generate correct relative Url from the action and controller name.

In some cases when Application is hosted in Inner directories our css stylesheets and js files do not load due to wrong Url.

Consider the scenario you are using the anchor tag with you first approach in the page and the View is in a nested Sub directory like Views -> Home -> Partials -> _Index.cshtml.

Now if you write anchor tag this way:

<a href="/About/Index">About</a>

now we are saying that go one directory back then About Controller and Index action but in current scenario the correct url will be:

<a href="../About/Index">About</a>

and writing anchor tag following will make sure Url is generated correct:

<a href="@Url.Action("Index","About")">About</a>

or:

Html.ActionLink(linkText:="About", controllerName:="About", actionName:="Index")

Using Plain hardcoded url causes issue like in this SO Post.

OP was facing issue ajax call was not getting to the action because of wrong Url, and using @Url.Action() helper solved the problem as it makes sure that Url is generated correct.

You should also read this informative article to make more clear understanding

这篇关于MVC - 为什么要使用ActionLink的而不是硬编码的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆