2017-08-07 35 views
1

私の目標はです。条件に応じてビューに渡されるモデルオブジェクトのステータスに応じてドロップダウンを無効にします。以下にはないタグヘルパーから<select>を条件付きで無効にするにはどうすればよいですか?

<select class="form-control" asp-for="Priority" asp-items="@priorityList" disabled></select> 

次のコードは正しく無効<select>タグ(ただし、条件付き)をレンダリングします。属性disabledは、レンダリングされたページのページソースに表示されない:

@{ string disabled = Model.CaseMode == Mode.Active ? "" : "disabled"; } 
<select class="form-control" asp-for="Priority" asp-items="@priorityList" @disabled></select> 

また、次のようにも<select>タグは無効になりません。

<select class="form-control" asp-for="Priority" asp-items="@priorityList" @((Model.CaseMode == Mode.Closed) ? "disabled" : "")></select> 

私は、問題は、文字列置換をテンプレートに行われる前に<select>タグを処理するタグヘルパーに関係していると仮定します。誰もがif else構造内の2つの別々の要素をレンダリングすることなく、この要素を条件付きで無効にする方法を提案できますか?

答えて

2

デフォルトのselectタグヘルパーでは不可能ですが、自分で作成してブール値を受け入れるカスタムasp-disabled属性に反応するように設定することができます。あなたのビューで

<select class="form-control" asp-for="Priority" asp-items="@priorityList" asp-disabled="@(Model.CaseMode == Mode.Closed)"></select> 

次に、あなたのTagHelperクラスを作成:あなたのTagHelperを確保するために

using Microsoft.AspNetCore.Razor.TagHelpers; 
using System; 

namespace YourNamespace.TagHelpers 
{ 
    // Triggered on all select elements with the asp-disabled attribute 
    [HtmlTargetElement("select", Attributes = DisabledAttributeName)] 
    public class SelectTagHelper : TagHelper 
    { 
     private const string DisabledAttributeName = "asp-disabled"; 

     /// Get the value of the condition 
     [HtmlAttributeName(DisabledAttributeName)] 
     public bool Disabled { get; set; } 

     public override void Process(TagHelperContext context, TagHelperOutput output) 
     { 
      if (context == null) 
       throw new ArgumentNullException(nameof(context)); 

      if (output == null) 
       throw new ArgumentNullException(nameof(output)); 

      if (Disabled) 
       output.Attributes.SetAttribute("disabled", null); 
     } 
    } 
} 

が使用されている、あなたはまた、_ViewImports.cshtmlに登録する必要があります:

@addTagHelper *, YourNamespace 
+0

ありがとうございました。これはフレームワークで提供されている既存の '