TagBuilder.MergeAttributes not working

I am creating my own helper in MVC. But custom attributes are not added to HTML:

Assistant

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

End result (HTML)

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

Note that he did not add the gradient-top class that I mentioned in the helper call.

+6
source share
2 answers

When calling MergeAttributes with replaceExisting set to false , it simply adds attributes that do not currently exist in the attribute dictionary. It does not combine / do not combine the values โ€‹โ€‹of individual attributes.

I believe that you will go to

 builder.AddCssClass("selected"); 

after

 builder.MergeAttributes(attributes, false); 

will fix your problem.

+18
source

I wrote this extension method that does what MergeAttributes should have thought (but when checking the source code, it just skips the existing attributes):

 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
source

Source: https://habr.com/ru/post/891119/


All Articles