2017-02-20 80 views

回答

5

能力按照tagHelper提供补充条件CSS类。 此代码类似AnchorTagHelper asp-route- *用于添加路由值的行为。

[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); 
     } 
    } 
} 
在_ViewImports.cshtml

添加参考taghelper在查看以下

@addTagHelper "*, WebApplication3" 

使用tagHelper:

<div condition-class-active="Model.Active" condition-class-show="Model.Display"> 
</div> 

结果为Active =真实,显示=真:

<div class="active show"> 
</div> 
+0

是否可以使用后缀,而不仅仅是pref ixes?说'class - * - if'? – Serge

+0

@Serge从内联文档中,*可能只出现在最后。所以今天可能不可能。 – ygoe

+0

当我使用上述代码示例时,它呈现'

' – mheptinstall

2

有没有默认的方式来做你在问什么。你将不得不写一个TagHelper来为你做这个逻辑。阿卡

[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看起来像:

<div class="choice" asp-active="Model.Active"></div> 
相关问题