Search code examples
razorasp.net-core-mvcasp.net-core-2.1

Asp.Net Core 2.1.0-preview1-final: @Html.ActionLink() is not working for string.Format()


<div data-collapse class="left-justify" id="requirements">
  @Html.Raw(string.Format(@_stringLocalizer["RegisterNoticeMessage"], @Html.ActionLink(@_stringLocalizer["RegisterLinkDisplayName"], "Register")))
</div>

In this piece of code, @Html.ActionLink() is returning Microsoft.AspNetCore.Mvc.Rendering.TagBuilder instead of returning anchor element containing URL path to the specified action. What is the right way to use @Html.ActionLink() in string.Format(). Or, do I missing anything, here?


Solution

  • The helper method Html.ActionLink always returns a TagBuilder object. When you pass such an object into a string parameter, the ToString() method will be called, resulting in your observed output (the class name: "Microsoft.AspNetCore.Mvc.Rendering.TagBuilder").

    It seems to me you are trying to create a hyperlink in a rather weird way. Have you tried using the Url.Action helper method? This method returns a plain old string, ready to plug into any href attribute.

    E.g. this code would be equivalent of what you're trying to achieve:

    @Html.Raw(
        string.Format(_stringLocalizer["RegisterNoticeMessage"], 
        "<a href=\"" + Url.Action("Register") + "\">" + _stringLocalizer["RegisterLinkDisplayName"] + "</a>")
    )
    

    Sidenotes:

    • It is possible get the string value of a TagBuilder, as illustrated in this post.
    • No need to repeat @ when you're already working in Razor/C# context.
    • Be extremely careful when using Html.Raw as it might result in XSS vulnerabilities.