在 Actionlink 中做原始 HTML

Do raw HTML in Actionlink

我有这个动作link

@Html.ActionLink("<i class='fa fa-sign-out'></i>" + ecHelpers.GetLabel("Log out"), "Logout", "MyAccountSurface", new { Class = "" })

如何将 html 设为 html 而不是

对于这种情况,您可以使用 @Url.Action:

<a href="@Url.Action("Logout", "MyAccountSurface")">
    <i class='fa fa-sign-out'></i>@ecHelpers.GetLabel("Log out")
</a>

注意:我不确定此处对 ecHelpers.GetLabel 的调用在句法上是否正确,但您明白了。

通常您会将助手调用嵌套在您希望它显示的标签中,例如:

<i class='fa fa-sign-out'>
    @Html.ActionLink(ecHelpers.GetLabel("Log out"), "Logout", "MyAccountSurface", new { Class = "" })
</i>

我制作了这个扩展方法以使其更容易:

    public static MvcHtmlString RawActionLink(this HtmlHelper htmlHelper, string linkHtml, string actionName, string controllerName, object routeValues, object htmlAttributes)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var url = urlHelper.Action(actionName, controllerName, routeValues);
        var attributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        var concatenatedHtmlAttributes = string.Join(" ", attributeDictionary.Select(a => string.Format("{0}=\"{1}\"", a.Key, HttpUtility.HtmlAttributeEncode(a.Value.ToString()))));            
        var link = string.Format("<a href=\"{0}\" {1}>{2}</a>", url, concatenatedHtmlAttributes, linkHtml);
        return new MvcHtmlString(link);
    }