Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of using MVC HTML helpers like ActionLink, BeginForm, TextBox, etc instead of the native HTML tags?

In a SO response to a different question, a user stated that it allowed you to avoid hard-coding route values into a html link tag, but that is not really valid since you have to put in the controller, action, area, etc as strings so you are still hard-coding the route values.

How is this:

@Html.ActionLink(linkText: "MyLink", actionName: "MyAction", controllerName: "MyController", new { id = @myId }, new { area = "SomeArea"})

better than this:

<a href='/SomeArea/MyController/MyAction/myId'>MyLink</a>
like image 461
jpshook Avatar asked Feb 02 '12 15:02

jpshook


1 Answers

Your observation is only true if (a) you're using strictly the default routing format and (b) if your application will always be installed at the root of the site. If you don't do the former (say create a short cut route /help which goes to the Home controller and Help action, and subsequently change it by introducing a Help controller with more actions, then you'll need to update all of your hard-coded anchor tags. A better alternative is using the RouteLink helper with the route name and, optionally, other parameters.

With regard to the latter, I typically use a single server for most of my staging deployments and the application does NOT sit at the site root, but rather in a subdirectory. Production deployment is mixed, but many applications get installed at the site root. Using the helpers allows me to ignore the difference during development as the helper properly constructs the url relative to the current site in all cases. This is so helpful that I even use it for scripts, css files, images, etc. via the UrlHelper to make sure that any paths specified for those do not break between staging and production.

like image 141
tvanfosson Avatar answered Oct 12 '22 23:10

tvanfosson