如何为Html.ActionLink(MVC3)合并htmlAttributes?

Sha*_*dix 4 c# html-helper asp.net-mvc-3

我将编写一个包装Html.ActionLink的简单助手,并为其添加一个类属性.目前它看起来像:

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

它实际上添加了所需的@class属性,但忽略了所有传递的属性htmlAttributes.所以,如果像使用一样

@MyActionLink("Item1", "Edit", new { itemId = 1 }, new { @class = "class1" })
Run Code Online (Sandbox Code Playgroud)

它输出

<a class="MyClass" href="/Test/Edit?itemId=1">Item1</a>
Run Code Online (Sandbox Code Playgroud)

但我希望它有2个类: class="class1 MyClass"

如何合并这些htmlAttributes?

haz*_*zik 8

试试这个片段

@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)
}
Run Code Online (Sandbox Code Playgroud)