Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing html attributes to Html.Actionlink helper function

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

like image 288
Mohsin Avatar asked Feb 15 '23 18:02

Mohsin


2 Answers

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.

like image 104
Jos Vinke Avatar answered Mar 08 '23 04:03

Jos Vinke


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)
like image 30
Davor Zlotrg Avatar answered Mar 08 '23 05:03

Davor Zlotrg