2011-06-22 7 views
6

Estoy creando mi propio ayudante en MVC. Sin embargo, los atributos personalizados no se agregan en el código HTML:TagBuilder.MergeAttributes no funciona

ayudante

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" }) 

resultado final (HTML)

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

Tenga en cuenta que no agregó la clase gradient-top que mencioné en la llamada auxiliar.

Respuesta

18

Al llamar MergeAttributes con replaceExisting conjunto de false, que sólo añade los atributos que no existen actualmente en el diccionario de los atributos. No fusiona/concatena los valores de los atributos individuales.

creo moviendo su llamada a

builder.AddCssClass("selected"); 

después

builder.MergeAttributes(attributes, false); 

va a arreglar el problema.

0

he escrito este método de extensión que hace lo que yo pensaba MergeAttributes tenía que hacer (pero al comprobar el código fuente que sólo se salta los atributos existentes):

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; 
     } 
    } 
}