このTagBuilder.MergeAttributes
方法は、期待どおりに機能しません。これは、このメソッドの正確なコードです。
public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting)
{
if (attributes != null)
{
foreach (var entry in attributes)
{
string key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
string value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture);
MergeAttribute(key, value, replaceExisting);
}
}
}
public void MergeAttribute(string key, string value, bool replaceExisting)
{
if (String.IsNullOrEmpty(key))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "key");
}
if (replaceExisting || !Attributes.ContainsKey(key))
{
Attributes[key] = value;
}
}
ご覧のとおり、コレクションに新しい属性を追加するだけです(replaceExisting
trueに設定されている場合は、コレクションに既に存在する属性も置き換えられます)。ロジックをマージする値を実行および属性付けしません。値をマージする場合は、自分で行う必要があります。
public static MvcHtmlString List(this HtmlHelperhelper, object htmlAttributes)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (attributes.ContainsKey("class"))
attributes["class"] = "myclass " + attributes["class"];
else
attributes.Add("class", "myClass");
var tag = new TagBuilder("div");
tag.MergeAttributes(attributes, false);
return new MvcHtmlString(tag.ToString(TagRenderMode.Normal));
}