Render link containing span in ASP.net MVC Razor?

后端 未结 2 469
无人共我
无人共我 2021-01-26 12:08

Rendering a simple link is easy:

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

But how would you write the following in razor syntax:

相关标签:
2条回答
  • 2021-01-26 12:23

    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.

    0 讨论(0)
  • 2021-01-26 12:40

    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>
    
    0 讨论(0)
提交回复
热议问题