2017-02-20 23 views

答えて

5

tagHelper提供に従うことによって、条件付きCSSクラスを追加する機能。 このコードは、ルート値を追加するための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への参照を追加します。=アクティブ真と表示=真のため

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

結果は次のとおりです。

<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> 
関連する問題