首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TagBuilder.MergeAttributes不工作

TagBuilder.MergeAttributes不工作
EN

Stack Overflow用户
提问于 2011-06-22 14:15:07
回答 2查看 4.6K关注 0票数 6

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

Helper

代码语言:javascript
复制
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

代码语言:javascript
复制
@Html.MenuItem("nossa igreja2", "Index", "Home", new { @class = "gradient-top" })

最终结果()

代码语言:javascript
复制
<li class="selected"><a href="/">nossa igreja2</a></li>

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-08-09 22:23:38

当调用MergeAttributes并将replaceExisting设置为false时,它只会添加属性字典中当前不存在的属性。它不合并/合并单个属性值。

我相信把你的电话转到

代码语言:javascript
复制
builder.AddCssClass("selected");

之后

代码语言:javascript
复制
builder.MergeAttributes(attributes, false);

会解决你的问题。

票数 18
EN

Stack Overflow用户

发布于 2014-02-05 20:58:04

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

代码语言:javascript
复制
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;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6441370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档