[英]TagBuilder.MergeAttributes does not work
我在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>
请注意,它没有添加我在helper调用中提到的类gradient-top
。
当调用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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.