Reputation: 10710
I'm working on a localization project and I need to convert an anchor tag to use the @Html.ActionLink
instead.
I have this html helper:
@helper RenderIcon(bool condition, string @class, string title, string url, bool openInNewWindow = false)
{
if (condition)
{
<a href="@(new MvcHtmlString(url))" @(openInNewWindow ? " target='_blank'" : "")>
@(this.RenderIconSpan(@class, title))
</a>
}
}
I've come up with this:
@Html.ActionLink(this.RenderIconSpan(@class, title), url, null, openInNewWindow ? new { target="_blank" } : null)
But I get this error:
Cannot resolve method ... candidates are ...
If I need to provide more information please comment and I'll provide that. I've never converted an anchor tag this complex into an ActionLink
and I'm not sure that the ternary operator is correct along with everything else I've done.
Upvotes: 3
Views: 1142
Reputation: 18877
You cannot have nested elements using the out of the box Html.ActionLink
functions. You will have to create an overload which takes something like an MvcHtmlString
and inserts it into the anchor.
public static IHtmlString ActionLink(this HtmlHelper html, IHtmlString innerHtml, string action, string controller, IDictionary<string, object> htmlAttributes)
{
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var tag = new TagBuilder("a");
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("href", urlHelper.Action(action, controller));
return new HtmlString(tag.ToString(TagRenderMode.Normal));
}
(from memory, so you'll have to work out some kinks I'm sure)
Upvotes: 2
Reputation: 931
Here is Hack (low and dirty) workaround in case you need to use ajax or some feature which you cannot use when making link manually (using tag):
<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class='large sprite refresh'></span>")%>
You can use any text instead of 'LinkTextToken', it is there only to be replaced, it is only important that it does not occur anywhere else inside actionlink.
Upvotes: 2