4

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?

3 Answers 3

8

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! Nice to know that RouteValueDictionary's ctor accepts and parses objects.
I've just seen sources and advise to use HtmlHelper.AnonymousObjectToHtmlAttributes for convertion, because it does some conversion on object property names (such as replace _ with -)
1

This can be achieved simply appending tag in jquery script like this,

$("#linkID").html("<span class='ui-icon ui-icon-gear'/>"+$("#linkID").html());

Comments

0

A bit simpler than hazzik's answer:

@helper MyActionLink(string text, string action, object routeValues, object htmlAttributes)
{
    var htmlAttr = HtmlHelper.AnonymousObjectToHtmlAttributes(this.ViewData["htmlAttributes"]);

    htmlAttr["class"] = ("MyClass " + htmlAttr["class"]).Trim();

    @Html.ActionLink(text, action, new RouteValueDictionary(routeValues), htmlAttr)
}

1 Comment

I guess this.ViewData["htmlAttributes"]) should be htmlAttributes.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.