質問

ASP.NET MVCビューに、次の形式のリンクを含めたい:

<a href="blah">Link text <span>with further descriptive text</span></a>

<span>の呼び出しのlinkTextフィールドにHtml.ActionLink()要素を含めようとすると、(予想どおり)エンコードされてしまいます。

これを達成するための推奨される方法はありますか?

役に立ちましたか?

解決

Url.Actionを使用してリンクを作成できます:

<a href="<% =Url.Action("Action", "Controller")%>">link text <span>with further blablah</span></a>

またはHtml.BuildUrlFromExpressionを使用:

<a href="<% =Html.BuildUrlFromExpression<Controller>(c => c.Action()) %>">text <span>text</span></a>

他のヒント

Razorを使用したい場合、これは動作するはずです:

<a href="@Url.Action("Action", "Controller")">link text <span>with further blablah</span></a>

もう1つのオプションは、HTML.ActionLinkまたはAjax.ActionLink(コンテキストに応じて)を使用して、通常どおりにアクションリンクをMvcHtmlStringにレンダリングし、レンダリングされたMvcHtmlStringを取得してHTMLリンクテキストをハッキングするクラスを記述することです既にレンダリングされたMvcHtmlStringに直接接続し、別のMvcHtmlStringを返します。

これはそれを行うクラスです:[挿入/置換コードは非常に単純であり、ネストされたhtmlをさらに処理するには強化する必要があるかもしれないことに注意してください]

namespace Bonk.Framework
{
    public class CustomHTML
    {
        static public MvcHtmlString AddLinkText(MvcHtmlString htmlString, string linkText)
        {
            string raw = htmlString.ToString();

            string left = raw.Substring(0, raw.IndexOf(">") + 1);
            string right = raw.Substring(raw.LastIndexOf("<"));

            string composed = left + linkText + right;

            return new MvcHtmlString(composed);
        }
    }
}

そして、次のようにビューで使用します:

@Bonk.Framework.CustomHTML.AddLinkText(Ajax.ActionLink("text to be replaced", "DeleteNotificationCorporateRecipient"), @"Link text <span>with further descriptive text</span>")

このアプローチには、タグのレンダリングプロセスを再現/理解する必要がないという利点があります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top