Render link containing span in ASP.net MVC Razor?

2019-03-05 11:49发布

Rendering a simple link is easy:

@Html.ActionLink("About this Website", "About")

But how would you write the following in razor syntax:

<a>
    <span>Hello, I'm inconvenient!</span>
</a>

Appreciate any point in the right direction :)

2条回答
不美不萌又怎样
2楼-- · 2019-03-05 12:02

You can create a custom Html Helper, and can reuse it in any View in application:

namespace MyApplication.Helpers
{
  public static class CustomHtmlHelepers
  {
    public static IHtmlString ActionLinkWithSpan(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes)
    {
       var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
       var span = new TagBuilder("span") { InnerHtml = linkText };
       var anchor = new TagBuilder("a") { InnerHtml = span.ToString() };
       anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
       anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));

       return MvcHtmlString.Create(anchor.ToString());

    }
  }
}

and use it in View:

@using MyApplication.Helpers;

@Html.ActionLinkWithSpan("LinkText","ActionName","ControllerName",null,null)

Output HTML:

<a href="/ControllerName/ActionName">
<span>LinkText</span>
</a>
查看更多
Melony?
3楼-- · 2019-03-05 12:04

I'm not sure I follow your example properly as it doesn't contain a link and the text for the link is different to that of the span but something like this should give you a general idea:

<a href='@Url.Action("About")'>
    <span>Hello, I'm inconvenient!</span>
</a>

Using Url.Action() will return the actual hyperlink rather than the element.

查看更多
登录 后发表回答