我正在用MVC创建自己的助手。但是,自定义属性没有添加到HTML中:
Helper
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" })最终结果()
<li class="selected"><a href="/">nossa igreja2</a></li>注意,它没有添加我在助手调用中提到的类gradient-top。
发布于 2011-08-09 22:23:38
当调用MergeAttributes并将replaceExisting设置为false时,它只会添加属性字典中当前不存在的属性。它不合并/合并单个属性值。
我相信把你的电话转到
builder.AddCssClass("selected");之后
builder.MergeAttributes(attributes, false);会解决你的问题。
发布于 2014-02-05 20:58:04
我编写了这个扩展方法,实现了认为 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;
}
}
}https://stackoverflow.com/questions/6441370
复制相似问题