4

i want to know that how to pass html attributes to @Html.ActionLink helper function

i want to do like that

<a class="accordion-toggle" data-toggle="collapse" data-parent="#leftMenu" href="/Admin/UserManagment">
                    <i class="icon-user"></i>User Managment
                </a>

how to pass that italic html attribute

2 Answers 2

6

You could use @Url.Action() as an alternative.

In this case your code would look like this:

<a class="accordion-toggle" data-toggle="collapse" data-parent="#leftMenu" 
    href="@Url.Action("UserManagment", "Admin")">
        <i class="icon-user"></i>User Managment
</a>

Edit:

Out of interest I did a bit of research and found this answer. Which explains it isn't possible to use the Html.ActionLink for this purpose:

The Html.ActionLink helper HTML encodes the link text which prevents you from embedding HTML in the link text.

3
  • this is not what i asked
    – Mohsin
    Nov 5, 2013 at 12:19
  • Sorry I updated my answer, I didn't read the last line, hopefully this answer is more helpfull.
    – Jos Vinke
    Nov 5, 2013 at 12:39
  • It's really helpful for me :D
    – Ananda G
    Aug 11, 2016 at 10:44
2

There is no way to wrap html code inside the anchor tag using @Html.ActionLink

You can use @Url.Action

<a href="@Url.Action("UserManagment", "Admin")" ...>
    <i class="icon-user"></i>User Managment
</a>

Or create an extension method:

public static IHtmlString MyActionLink(this HtmlHelper helper,
                                            string value, 
                                            Dictionary<string, string> attributes,
                                            string innerHtml)
{
    var aBuilder = new TagBuilder("a");
    foreach (var attr in attributes)
    {
        aBuilder.MergeAttribute(attr.Key, attr.Value);
    }
    aBuilder.InnerHtml += innerHtml + value;

    return new HtmlString(aBuilder.ToString(TagRenderMode.Normal));
}

And use it in your views like this

@{
    var attributes = new Dictionary<string, string>
        {
          { "data-toggle", "collapse" },
          { "data-parent", "#leftMenu" },
          { "href", Url.Action("UserManagement", "Admin") }
        };
    var innerHtml = "<i class='icon-user'></i>";
}

@Html.MyActionLink("User Managment", attributes, innerHtml)

Your Answer

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

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