2011-06-22 1 views
6

私はMVCで自分のヘルパーを作成しています。しかし、カスタム属性をHTMLに追加されていません。TagBuilder.MergeAttributesが機能しません

ヘルパー

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を追加していないことに注意してください。

答えて

18

falseからreplaceExistingセットでMergeAttributesを呼び出し、それだけで、現在の属性の辞書には存在しない属性を追加します。個々の属性の値をマージ/連結しません。

私はあなたの問題を解決します

builder.MergeAttributes(attributes, false); 

builder.AddCssClass("selected"); 

にお電話を動かすと信じています。

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; 
     } 
    } 
} 
関連する問題