Creating HTML hyperlinks Html.ActionLink in MVC

Home > Search
  by

Classic HTML can produce long, and sometimes unweildy URLs. MVC is much more elegant. Let's start by looking at how HTML handles navigating around different pages. The following is the syntax of the markup to transform the text "Learn more" into a hyperlink that redirects to Content page in classic HTML. In this example, the URL will be http://www.example.com/Content.html.

<a href="Content.html"> Learn more </a>

 

In MVC, the following is the syntax of the markup to transform the text Go into a hyperlink that redirects to a new page. In this example, the URL will be http://www.example.com/Content. Notice the URL does not end in ".html", yet we still get the Content page.

@Html.ActionLink("Go", "Content")

 

It is likely that the Content page consists of a default index.cshtml page, such as /Content/Index.cshtml. If we create an ActionLink that direct to these Index page, the web browser may produce a 403 forbidden error.

@Html.ActionLink("Go", "Index", "Content")

 

To prevent the 403 Forbidden error, we can adding a route to the /Content/Index page in the /App_Start/RouteConfig.cs file:

routes.MapRoute(
  "Content",
  "{controller}/{action}/{id}",
  new { controller = "Content", action = "Index", id = UrlParameter.Optional }
);

 

Now when requesting the /Content/Index page, the URL only displays www.example.com. In another words, the URL does not display as www.example.com/Content/Index.


SQL database

If the destination page gets data from a SQL database, probably will need to appened ID to the ActionLink, which will produce a URL such as www.example.com/Content/Index/1. To accomplish this, add new {id=item.id}, null. We can also replace the first field with item.column_name:

@Html.ActionLink(item.column_name, "Index", "Content", new {id=item.id }, null)

 

To apply CSS to the URL, add new {@class="sample"} to the end, replacing sample with the name of the CSS class.

@Html.ActionLink(item.column_name, "Index", "Content", new {id=item.id }, new { @class = "sample" })

 


To link to an external URL:

<a href="http://@item.url"> Go </a>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments