将HTML放在Html.ActionLink()中,加上没有链接文本?

Meg*_*att 162 .net c# asp.net-mvc actionlink

我有两个问题:

  1. 我想知道Html.ActionLink()在MVC视图中使用时我怎么能显示没有链接文本(实际上,这是Site.Master).

没有一个不允许链接文本的重载版本,当我尝试只传入一个空白时string,编译器告诉我它需要一个非空字符串.

我怎样才能解决这个问题?

  1. 我需要<span>在锚标记中放置标记,但它不能使用Html.ActionLink();.我想看看以下输出:

    跨文本

如何在ASP.NET MVC中将标记放在锚标记内?

Dav*_*vid 313

您可以通过Url.Action呈现网址,而不是使用Html.ActionLink

<a href="<%= Url.Action("Index", "Home") %>"><span>Text</span></a>
<a href="@Url.Action("Index", "Home")"><span>Text</span></a>
Run Code Online (Sandbox Code Playgroud)

你可以做一个空白的网址

<a href="<%= Url.Action("Index", "Home") %>"></a>
<a href="@Url.Action("Index", "Home")"></a>
Run Code Online (Sandbox Code Playgroud)

  • 我不得不使用<a href="@Url.Action("Index","Home")"> <span> Text </ span> </a>,我的开发人员不在问我为什么要这么做这可能对任何人使用上述答案并发现它不起作用可能会有所帮助. (3认同)
  • @ Url.Action是使用剃刀模板的时候.我已经更新了答案,你可以看到两者. (2认同)
  • 对于静态内容,为什么不直接键入 html?它似乎不那么冗长和简单 (2认同)

tva*_*son 17

自定义HtmlHelper扩展是另一种选择. 注意:ParameterDictionary是我自己的类型.您可以替换RouteValueDictionary,但您必须以不同方式构造它.

public static string ActionLinkSpan( this HtmlHelper helper, string linkText, string actionName, string controllerName, object htmlAttributes )
{
    TagBuilder spanBuilder = new TagBuilder( "span" );
    spanBuilder.InnerHtml = linkText;

    return BuildNestedAnchor( spanBuilder.ToString(), string.Format( "/{0}/{1}", controllerName, actionName ), htmlAttributes );
}

private static string BuildNestedAnchor( string innerHtml, string url, object htmlAttributes )
{
    TagBuilder anchorBuilder = new TagBuilder( "a" );
    anchorBuilder.Attributes.Add( "href", url );
    anchorBuilder.MergeAttributes( new ParameterDictionary( htmlAttributes ) );
    anchorBuilder.InnerHtml = innerHtml;

    return anchorBuilder.ToString();
}
Run Code Online (Sandbox Code Playgroud)


Gor*_*vic 13

这是(低和脏)解决方法,以防您需要使用ajax或手动链接时使用的某些功能(使用标记):

<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class='large sprite refresh'></span>")%>
Run Code Online (Sandbox Code Playgroud)

您可以使用任何文本而不是'LinkTextToken',它只是被替换,重要的是它不会发生在actionlink内的任何其他地方.

  • +1好主意.在Razor中,你必须在`Html.Raw()`中说出所有这些内容 (6认同)

Cra*_*ntz 12

只需使用Url.Action而不是Html.ActionLink:

<li id="home_nav"><a href="<%= Url.Action("ActionName") %>"><span>Span text</span></a></li>
Run Code Online (Sandbox Code Playgroud)


dba*_*rth 6

这对我来说一直很好.它并不凌乱,非常干净.

<a href="@Url.Action("Index", "Home")"><span>Text</span></a>