简体   繁体   中英

How to convert anchor tag HTML links to use @Html.ActionLink

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM