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 andHtml.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:
now we are saying that go one directory back then About Controller and Index action but in current scenario the correct url will be:
and writing anchor tag following will make sure Url is generated correct:
or:
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