Monday, June 29, 2015

Use Anchor Tag for calling an Action in MVC

 If you are trying to call a "Action" from the Anchor tag in MVC below is the way to do it.


<a href="@Url.Action("ActionName", "ControllerName", new { area = "AreaName" })">LinkText</a>


Example:

<a href="@Url.Action("Registration", "Account", new { area = "ManageAccount" })">Regsitration</a>


You can also do the same in below way as well.
@Html.ActionLink("Registration", "Registration", "Account", new { area = "ManageAccount" }, null)



Then, is there any difference between the Url.Action and @Html.ActionLink?


Yes, there is a difference. Html.ActionLink generates an <a href=".."></a> tag

But, Url.Action returns only an url.


For example:

@Html.ActionLink("LinkText", "action", "controller", new { id = "123" }, null)

generates:


<a href="/ controller/action /123"> LinkText </a>


Where as Url.Action("action", "controller", new { id = "123" }) generates:

/controller/action/123