Reputation: 67193
I'm new to MVC and would like to add a link to something like ~/Destinations/35
, where it would refer to the Index view of the Destinations controller, and 35 is the ID of the destination to be displayed.
Neither ActionLink() or RouteLink() appear to allow me to create a link such as this.
Also, I tried something like this:
<table>
@foreach (var d in ViewBag.Results)
{
<tr>
<td>
@Html.ActionLink(
String.Format("<b>{0}</b>", @Html.Encode(d.Title)),
"Details", "Destinations")
</td>
</tr>
}
</table>
But I get the following error on the ActionLink line, which I don't understand.
'System.Web.Mvc.HtmlHelper' has no applicable method named 'ActionLink' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
Can someone help me create this link?
Upvotes: 1
Views: 1231
Reputation: 1038810
The first problem with your code is that you are trying to use HTML in the link text (the <b>
tags) which is not possible because by design it always HTML encodes.
So assuming you didn't want HTML in the link you could do this:
@Html.ActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
And assuming you need HTML inside the anchor you have a couple of possibilities:
Write a custom ActionLink helper which won't HTML encode the text (recommended) and then use like this:
@Html.MyBoldedActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
Something along the lines:
<a href="@Url.Action("Details", "Destinations", new { id = "35" })">
<b>@d.Title</b>
</a>
and since I recommend the first approach here's a sample implementation of the custom helper:
public static class HtmlExtensions
{
public static IHtmlString MyBoldedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes
)
{
var anchor = new TagBuilder("a");
anchor.InnerHtml = string.Format("<b>{0}</b>", htmlHelper.Encode(linkText));
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
anchor.Attributes["href"] = urlHelper.Action(actionName, controllerName, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return new HtmlString(anchor.ToString());
}
}
Upvotes: 5