MVC - why use ActionLink instead of hard coding the link?

3.6k views Asked by At

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

3

There are 3 answers

1
Ehsan Sajjad On BEST ANSWER

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

1
Kenan Zahirovic On

Fully agree with @Ehsan: ActionLink helper can save you a lot of troubles when moving application to web server (relative path).

Also, ActionLink is better, because if you latter change your Controller or Action name, compiler should warn you.

On the other side, "a href..." is not able to see the error before run-time error occurs.

1
Siva Gopal On

+1 Try using MVC Helpers to generate urls as much as you can since you can leverage:

1) Take advantage of ASP.NET MVC's outgoing url generation from route templates. So even if you happen to change/version your route template the url generated via helpers can regenerate those url properly. Thus the links are not broken.

2) They have nice overloads which improve readability and much cleaner as well E.g. Using anonymous types for route values and html attributes etc instead of ugly concatinations

3) You can include them within script also as server tags so that same links generated across based on url generation scheme.