TagBuilder.MergeAttributes не работает
Я создаю свой собственный помощник в 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
что я упомянул во вспомогательном вызове.
2 ответа
Решение
При звонке MergeAttributes
с replaceExisting
установлен в false
, он просто добавляет атрибуты, которые в настоящее время не существуют в словаре атрибутов. Он не объединяет / не объединяет значения отдельных атрибутов.
Я верю, что ваш звонок
builder.AddCssClass("selected");
после
builder.MergeAttributes(attributes, false);
исправит вашу проблему.
Я написал этот метод расширения, который делает то, что, как я думал, должен делать 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;
}
}
}