简体   繁体   English

如何将锚标记HTML链接转换为使用@ Html.ActionLink

[英]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. 我正在开发本地化项目,我需要将锚标记转换为使用@Html.ActionLink

I have this html helper: 我有这个HTML帮助器:

@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. 我从来没有将这个复合体的锚标签转换为ActionLink ,我不确定三元运算符是否正确以及我所做的其他事情。

You cannot have nested elements using the out of the box Html.ActionLink functions. 使用开箱即用的Html.ActionLink函数不能拥有嵌套元素。 You will have to create an overload which takes something like an MvcHtmlString and inserts it into the anchor. 您将不得不创建一个重载,它接受类似MvcHtmlString东西并将其插入到锚点中。

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): 这里是Hack(低和脏)解决方法,以防您需要使用ajax或手动链接时使用的某些功能(使用标记):

<%= 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. 您可以使用任何文本而不是'LinkTextToken',它只是被替换,重要的是它不会发生在actionlink内的任何其他地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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