Archive

Archive for September, 2013

Html.ActionLink VS Html Anchar Tag ()

September 18, 2013 Leave a comment

Here ,in this post i am going to describe about MVC Html.ActionLink and normal anchor tag and which one is best for use.

Html.ActionLink

Html.ActionLink use current routing configuration in Gloabl.asax.cs to prepare hyperlink at runtime. so when you modify your routing setting in said global file then Html.ActionLink directly  reference modified routing settings that you will  see below in this blog.

Anchar Tag ()

if  you use anchar tag then there is chance that your links will be broken in case routing configuration in Gloabl.asax.cs is changed. So always use Html.ActionLink over Anchar Tag that will save you time as you do not have to change all anchar tag manually  when routing configuration in Gloabl.asax.cs is changed .

Now, let’s experince this visually, Intially it is “Home/TestIndex” set as routing configuration in Gloabl.asax.cs as below and hyperlink is implemented in two way 1) Using Action Link 2) using Anchor Tag in view

Gloabl.asa


public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"CustomeTest", // Route name
"Home/TestIndex",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
<pre>

HTML that using hyperlink in two way 1) Using Action Link 2) using Anchor Tag

<div>
<a href="../../Home/TestIndex">Back to Home (Simple Anchor Tag) </a>
<br />
<br />
@Html.ActionLink("Back to Home (Mvc Action Link)", "Index")
</div>

Now see it visually

PIC1

Here , when Back to Home (Simple Anchor Tag) link is clicked  it redirecting to home page properly .Now let’s change routing setting from “Home/TestIndex” to “Home/SuperIndex” as below then try to access same link to go to Home Page.

Pic2

so When Route settings is changed in Global.asax file then Html.ActionLink is modified accordingly but simple Anchor tag remain same so when simple Anchor tag link is clicked then you will get page not found  as below. But when link made by Html.ActionLink is clicked then it is opening concerned page properly as its Url / Hperlink is modified according to the route settings in global file

Pic3Hope you got the concept behind Html.ActionLink over Simple Anchar tag . And yes , if this post interest you then do not forget to like and comment . You can download source code from here Download Me

Thanks for your time 🙂

%d bloggers like this: