:asp.net 핵심 태그 도우미 조건부 요소에 클래스를 추가하기위한
tagHelper를 사용하여이 작업을 수행하고 의해 다른 부분을 제거하는 방법<div class="choice @(Model.Active?"active":"")">
</div>
조건.
:asp.net 핵심 태그 도우미 조건부 요소에 클래스를 추가하기위한
tagHelper를 사용하여이 작업을 수행하고 의해 다른 부분을 제거하는 방법<div class="choice @(Model.Active?"active":"")">
</div>
조건.
능력을 : 아카
[HtmlTargetElement(Attributes = "asp-active")]
public class FooTagHelper : TagHelper
{
[HtmlAttributeName("asp-active")]
public bool Active { get; set; }
public override void Process(TagHelperOutput output, TagHelperContext context)
{
if (Active)
{
// Merge your active class attribute onto "output"'s attributes.
}
}
}
그리고 다음 HTML과 같을 것이다. 이 코드는 AnchorTagHelper asp-route- *와 같이 경로 값 추가 기능을 수행합니다.
_ViewImports.cshtml에서[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);
}
}
}
하는 것은보기에
@addTagHelper "*, WebApplication3"
사용 tagHelper을 다음과 같은 taghelper 참조를 추가 : 활동 = true로 표시 = 사실에 대한
<div condition-class-active="Model.Active" condition-class-show="Model.Display">
</div>
결과 것은 :
<div class="active show">
</div>
요청하는 것을 수행하는 기본 방법은 없습니다. 당신은 그 논리를 당신을 위해 TagHelper를 작성해야 할 것입니다. tagHelper 제공에 따라 조건부 CSS 클래스를 추가 할 수
<div class="choice" asp-active="Model.Active"></div>
접미사를 사용할 수 있습니다. pref ixes? 'class - * - if'라고 말할까요? – Serge
@Serge 인라인 설명서에서 *는 끝에 만 나타날 수 있습니다. 오늘은 불가능합니다. – ygoe
예제와 함께 위의 코드를 사용할 때 '
' – mheptinstall