When implementing a solution to an existing question for a helper conditional class helper in ASP.NET Core 2.0, I do not get the expected results.
The tag helper is a direct copy of a published response and has not been modified.
Following the example, instead of the class name, I get the full name of the attribute along with the specified class.
What am I doing wrong?
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);
}
}
}
}
controller
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);
}
Model
public class ConditionalTestViewModel
{
public bool Active { get; set; }
}
View
@model IEnumerable<ConditionalTestViewModel>
<div>Conditional Test</div>
@foreach(var c in Model)
{
<div condition-class-active="@c.Active">@c.Active</div>
}
Output
<div id="container-body" class="container">
<div>Conditional Test</div>
<div condition-class-active="conditional-class-active">True</div>
<div>False</div>
</div>
Update: As indicated, TagHelper condition-class-*not conditional-class-*, I updated my question, but the problem still remains.