177

I have two questions:

  1. I'm wondering how I can display no link text when using Html.ActionLink() in an MVC view (actually, this is Site.Master).

There is not an overloaded version that does not allow link text, and when I try passing in just a blank string, the compiler tells me it needs a non-empty string.

How can I fix this?

  1. I need to put <span> tags within the anchor tag, but it's not working with Html.ActionLink();. I'd like to see the following output:

    Span text

How can I put tags inside of the anchor tag in ASP.NET MVC?

2
  • 1
    What would be the purpose/use of having a blank action link?
    – David
    Dec 29, 2009 at 14:47
  • 2
    I'm using an image sprite for a navigation bar, and the <li> you're seeing is a particular navigation button (with size, background pos, etc specified in css stylesheet). But it must link to something, so I don't want to display the text. I want the sprite to do that for me.
    – Matt
    Dec 29, 2009 at 14:53

12 Answers 12

348

Instead of using Html.ActionLink you can render a url via Url.Action

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

And to do a blank url you could have

<a href="<%= Url.Action("Index", "Home") %>"></a>
<a href="@Url.Action("Index", "Home")"></a>
5
  • 3
    I had to use <a href="@Url.Action("Index", "Home")"><span>Text</span></a>, my dev isn't around to ask why I had to do this but it may be helpful for anyone tring to use the above answer and finding it didnt work.
    – Dave Haigh
    Jul 12, 2013 at 8:12
  • 4
    @Url.Action is when using razor template. I've updated the answer so you can see both.
    – David
    Jul 12, 2013 at 8:36
  • 1
    <a [email protected]("Create", "Product")><span>Create</span></a> also works. The quotes are not required.
    – David
    Sep 15, 2015 at 20:54
  • 2
    For static content why not type the html directly? It seems less verbose and simpler
    – SkeetJon
    Dec 2, 2015 at 7:57
  • 1
    Not a real option in Asp.Net Core 2 anymore if you want to use Ajax.
    – Zorkind
    Aug 9, 2018 at 1:05
16

A custom HtmlHelper extension is another option. Note: ParameterDictionary is my own type. You could substitute a RouteValueDictionary but you'd have to construct it differently.

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();
}
0
14

Here is (low and dirty) workaround in case you need to use ajax or some feature which you cannot use when making link manually (using tag):

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

You can use any text instead of 'LinkTextToken', it is there only to be replaced, it is only important that it does not occur anywhere else inside actionlink.

5
  • 6
    +1 Nice idea. In Razor, you'll have to rap all of that in Html.Raw() Jun 10, 2014 at 13:38
  • Thanks :) Now that I see what we used, I almost get embarrassed, doing these things on the server is such waste of server resources... Jun 10, 2014 at 18:16
  • 1
    As I'm using @Ajax.ActionLink and didn't feel like manually setting all the date- attributes, this is the best solution for me. +1
    – asontu
    Mar 15, 2017 at 16:07
  • Thanks, worked like a charm when I was also using Ajax.ActionLink. It didn't seem to slow down anything and I got to keep the same layout and styling. Mar 23, 2017 at 15:11
  • Just want to say, this does not work in .Net Core, ToHtmlString() has been removed in v2 not sure about v1
    – Zorkind
    Aug 9, 2018 at 1:03
13

Just use Url.Action instead of Html.ActionLink:

<li id="home_nav"><a href="<%= Url.Action("ActionName") %>"><span>Span text</span></a></li>
1
  • @CraigStunz why should we use Url.Action instead of Html.ActionLink ?
    – Roxy'Pro
    Sep 18, 2017 at 12:32
7

This has always worked well for me. It's not messy and very clean.

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

2
  • Url.Action does not have a constructor that will take htmlAttributes. Not the same as ActionLink. Aug 10, 2016 at 18:23
  • That's because it creates a URL, not an a tag Nov 2, 2021 at 13:49
3

I ended up with a custom extension method. Its worth noting, when trying to place HTML inside of an Anchor object, the link text can be either to the left, or to the right of the inner HTML. For this reason, I opted to provide parameters for left and right inner HTML - the link text is in the middle. Both left and right inner HTML are optional.

Extension Method ActionLinkInnerHtml:

    public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary<string, object> htmlAttributes = null, string leftInnerHtml = null, string rightInnerHtml = null)
    {
        // CONSTRUCT THE URL
        var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
        var url = urlHelper.Action(actionName: actionName, controllerName: controllerName, routeValues: routeValues);

        // CREATE AN ANCHOR TAG BUILDER
        var builder = new TagBuilder("a");
        builder.InnerHtml = string.Format("{0}{1}{2}", leftInnerHtml, linkText, rightInnerHtml);
        builder.MergeAttribute(key: "href", value: url);

        // ADD HTML ATTRIBUTES
        builder.MergeAttributes(htmlAttributes, replaceExisting: true);

        // BUILD THE STRING AND RETURN IT
        var mvcHtmlString = MvcHtmlString.Create(builder.ToString());
        return mvcHtmlString;
    }

Example of Usage:

Here is an example of usage. For this example I only wanted the inner html on the right side of the link text...

@Html.ActionLinkInnerHtml(
    linkText: "Hello World"
        , actionName: "SomethingOtherThanIndex"
        , controllerName: "SomethingOtherThanHome"
        , rightInnerHtml: "<span class=\"caret\" />"
        )

Results:

this results in the following HTML...

<a href="/SomethingOtherThanHome/SomethingOtherThanIndex">Hello World<span class="caret" /></a>
1

I thought this might be useful when using bootstrap and some glypicons:

<a class="btn btn-primary" 
    href="<%: Url.Action("Download File", "Download", 
    new { id = msg.Id, distributorId = msg.DistributorId }) %>">
    Download
    <span class="glyphicon glyphicon-paperclip"></span>
</a>

This will show an A tag, with a link to a controller, with a nice paperclip icon on it to represent a download link, and the html output is kept clean

1

Here is an uber expansion of @tvanfosson's answer. I was inspired by it and decide to make it more generic.

    public static MvcHtmlString NestedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName,
        string controllerName, object routeValues = null, object htmlAttributes = null,
        RouteValueDictionary childElements = null)
    {
        var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        if (childElements != null)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            var anchorTag = new TagBuilder("a");
            anchorTag.MergeAttribute("href",
                routeValues == null
                    ? urlHelper.Action(actionName, controllerName)
                    : urlHelper.Action(actionName, controllerName, routeValues));
            anchorTag.MergeAttributes(htmlAttributesDictionary);
            TagBuilder childTag = null;

            if (childElements != null)
            {
                foreach (var childElement in childElements)
                {
                    childTag = new TagBuilder(childElement.Key.Split('|')[0]);
                    object elementAttributes;
                    childElements.TryGetValue(childElement.Key, out elementAttributes);

                    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(elementAttributes);

                    foreach (var attribute in attributes)
                    {
                        switch (attribute.Key)
                        {
                            case "@class":
                                childTag.AddCssClass(attribute.Value.ToString());
                                break;
                            case "InnerText":
                                childTag.SetInnerText(attribute.Value.ToString());
                                break;
                            default:
                                childTag.MergeAttribute(attribute.Key, attribute.Value.ToString());
                                break;
                        }
                    }
                    childTag.ToString(TagRenderMode.SelfClosing);
                    if (childTag != null) anchorTag.InnerHtml += childTag.ToString();
                }                    
            }
            return MvcHtmlString.Create(anchorTag.ToString(TagRenderMode.Normal));
        }
        else
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributesDictionary);
        }
    }
2
  • 1
    It is great that you were inspired and have the ability to do this. However, I look at nested foreach statements and want to run. It simply it not maintainable by most developers. If it is pretty set in stone black box type extension method then possibly ok, but it has a code smell to it. Not easy on the eyes at all for something that is pretty simple. Thanks for your efforts though. Sep 12, 2014 at 21:28
  • I very much agree about nested for loops. For the sake of succinctness it is there. From an optimization stand point yes the nested for loop should be in its own private method, and parameters need to be asserted, the code needs to be much more defensive, etc. Oct 16, 2014 at 15:03
0

It's very simple.

If you want to have something like a glyphicon icon and then "Wish List",

<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")
0

My solution using bootstrap components:

<a class="btn btn-primary" href="@Url.Action("resetpassword", "Account")">
    <span class="glyphicon glyphicon-user"></span> Reset Password
</a>
0

Please try below Code that may help you.

 @Html.ActionLink(" SignIn", "Login", "Account", routeValues: null, htmlAttributes: new {  id = "loginLink" ,**@class="glyphicon glyphicon-log-in"** }) 
1
  • just simple add ,@class and then actual css class help me to solve my problem
    – Ahsanul
    Mar 14, 2015 at 21:44
0

please try this code:

@Html.Raw(@Html.ActionLink("text", "ActionName", "ControllerName", null, new { area = "Home" }).ToHtmlString().Replace("text", "<i class='fa fa-car sub-icon-mg' aria-hidden='true'></i> <span class='mini-sub-pro'>Link Text</span>"))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.