6

我正在 MVC 中创建自己的助手。但是自定义属性没有添加到 HTML 中:

帮手

public static MvcHtmlString MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName, object htmlAttributes)
{
    var currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
    var currentActionName = (string)helper.ViewContext.RouteData.Values["action"];

    var builder = new TagBuilder("li");

    if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase)
        && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
        builder.AddCssClass("selected");

    if (htmlAttributes != null)
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        builder.MergeAttributes(attributes, false); //DONT WORK!!!
    }

    builder.InnerHtml = helper.ActionLink(linkText, actionName, controllerName).ToHtmlString();
    return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}

CSHTML

@Html.MenuItem("nossa igreja2", "Index", "Home", new { @class = "gradient-top" })

最终结果 (HTML)

<li class="selected"><a href="/">nossa igreja2</a></li>

请注意,它没有添加gradient-top我在助手调用中提到的类。

4

2 回答 2

18

MergeAttributes当使用replaceExistingset to调用时false,它只是添加属性字典中当前不存在的属性。它不会合并/连接各个属性的值。

我相信将您的电话转至

builder.AddCssClass("selected");

builder.MergeAttributes(attributes, false);

将解决您的问题。

于 2011-08-09T22:23:38.000 回答
0

我编写了这个扩展方法,它完成了我认为MergeAttributes 应该做的事情(但在检查源代码时它只是跳过了现有属性):

public static class TagBuilderExtensions
{
    public static void TrueMergeAttributes(this TagBuilder tagBuilder, IDictionary<string, object> attributes)
    {
        foreach (var attribute in attributes)
        {
            string currentValue;
            string newValue = attribute.Value.ToString();

            if (tagBuilder.Attributes.TryGetValue(attribute.Key, out currentValue))
            {
                newValue = currentValue + " " + newValue;
            }

            tagBuilder.Attributes[attribute.Key] = newValue;
        }
    }
}
于 2014-02-05T20:58:04.583 回答