在ASP.Net Core 2.0中为条件类标记助手实现existing question的解决方案时,我没有得到预期的结果。
标记助手是已发布答案的直接副本,尚未修改。
按照示例而不是类名称,我将获得完整的属性名称以及指定的类。
我做错了什么?
TagHelper
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PerformanceTools.TagHelpers
{
[HtmlTargetElement("div", Attributes = ClassPrefix + "*")]
public class ConditionClassTagHelper : TagHelper
{
private const string ClassPrefix = "condition-class-";
[HtmlAttributeName("class")]
public string CssClass { get; set; }
private IDictionary<string, bool> _classValues;
[HtmlAttributeName("", DictionaryAttributePrefix = ClassPrefix)]
public IDictionary<string, bool> ClassValues
{
get
{
return _classValues ?? (_classValues = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase));
}
set
{
_classValues = value;
}
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var items = _classValues.Where(e => e.Value).Select(e => e.Key).ToList();
if (!string.IsNullOrEmpty(CssClass))
{
items.Insert(0, CssClass);
}
if (items.Any())
{
var classes = string.Join(" ", items.ToArray());
output.Attributes.Add("class", classes);
}
}
}
}
控制器
public IActionResult ConditionalTest()
{
List<ConditionalTestViewModel> model = new List<ConditionalTestViewModel>();
model.Add(new ConditionalTestViewModel { Active = true });
model.Add(new ConditionalTestViewModel { Active = false });
return View("ConditionalTest", model);
}
模型
public class ConditionalTestViewModel
{
public bool Active { get; set; }
}
查看
@model IEnumerable<ConditionalTestViewModel>
<div>Conditional Test</div>
@foreach(var c in Model)
{
<div condition-class-active="@c.Active">@c.Active</div>
}
输出
<div id="container-body" class="container">
<div>Conditional Test</div>
<div condition-class-active="conditional-class-active">True</div>
<div>False</div>
</div>
更新:正如指出TagHelper condition-class-*
而非conditional-class-*
,我已用此更新了我的问题,但问题仍然存在。
答案 0 :(得分:0)
根据您提到的question,您有拼写错误。您应该使用condition-class-active而不是conditional-class-active,如下所示:
<div>Conditional Test</div>
@foreach(var c in Model)
{
<div condition-class-active="@c.Active">@c.Active</div>
}
_ViewImports.cshtml中的添加对taghelper的引用,如下所示
@addTagHelper "*, WebApplication3"