Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge htmlAttributes for Html.ActionLink (MVC3)?

I'm going to write a simple helper that wraps Html.ActionLink and adds a certain class attribute to it. At the moment it looks like:

@helper MyActionLink(string text, string action, object routeValues, object htmlAttributes)
    {
    @Html.ActionLink(text, action, routeValues, new { @class = "MyClass" })
}

It actually adds needed @class attribute, but ignores all the passed htmlAttributes. So, if being used like

@MyActionLink("Item1", "Edit", new { itemId = 1 }, new { @class = "class1" })

it outputs

<a class="MyClass" href="/Test/Edit?itemId=1">Item1</a>

but I want it to have 2 classes: class="class1 MyClass"

How can I merge those htmlAttributes?

like image 325
Shaddix Avatar asked Jan 18 '23 19:01

Shaddix


1 Answers

Try this snippet

@helper MyActionLink(string text, string action, object routeValues, object htmlAttributes)
{
    var attributes = (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    object cssClass;
    if(attributes.TryGetValue("class", out cssClass) == false)
    {
        cssClass = "";
    }
    attributes["class"] = cssClass + " MyClass";

    @Html.ActionLink(text, action, new RouteValueDictionary(routeValues), attributes)
}
like image 62
hazzik Avatar answered Feb 07 '23 19:02

hazzik