2011-07-07 4 views
4

条件に基づいて、テキストボックスの読み取り専用プロパティを作成するには、筆者の助けが必要です。 しかし私は試みたが失敗した。 以下は私のサンプルコードです:テキストボックスの読み取り専用プロパティをtrueまたはfalseに設定する方法

string property= ""; 
if(x=true) 
{ 
    property="true" 
} 
@Html.TextBoxFor(model => model.Name, new { @readonly = property}) 

私の質問ですが:条件が偽であるにもかかわらず、私は、テキストボックスを作成したり編集することができませんか。

答えて

8

これは、HTMLのreadonly属性が、単なる存在が読み取り専用のテキストボックスを示すように設計されているためです。

私は値true|falseが属性によって完全に無視され、実際には推奨値はreadonly="readonly"と考えています。

テキストボックスを再度有効にするには、readonly属性をすべて削除する必要があります。

htmlAttributesプロパティがTextBoxForの場合、IDictionaryであるため、要件に基づいてオブジェクトを作成できます。

IDictionary customHTMLAttributes = new Dictionary<string, object>(); 

if(x == true) 
    // Notice here that i'm using == not =. 
    // This is because I'm testing the value of x, not setting the value of x. 
    // You could also simplfy this with if(x). 
{ 
customHTMLAttributes.Add("readonly","readonly"); 
} 

@Html.TextBoxFor(model => model.Name, customHTMLAttributes) 

カスタムattrbuteを追加するための簡単な方法は次のようになります。単に

var customHTMLAttributes = (x)? new Dictionary<string,object>{{"readonly","readonly"}} 
                  : null; 

か:

@Html.TextBoxFor(model => model.Name, (x)? new {"readonly","readonly"} : null); 
+0

最後の行は動作しませんchieved。あなたの短略テストは間違って書かれており、可能でもありません。私は "無効な匿名型メンバー宣言子" Visual Studioエディタから取得します。 – Johncl

1
おそらく

の線に沿って何かであるためにあなたのコードをリファクタリングする必要があります

if(x) 
{ 
    @Html.TextBoxFor(model => model.Name, new { @readonly = "readonly"}) 
} 
else 
{ 
    @Html.TextBoxFor(model => model.Name) 
} 
+0

x = trueは常にtrueなので、常に読み込み専用のテキストボックスになります。 –

+0

申し訳ありません、元のコピー/貼り付けからでした。 – Treborbob

3

aそれは

public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled) 
    { 
     string rawstring = htmlString.ToString(); 
     if (disabled) 
     { 
      rawstring = rawstring.Insert(rawstring.Length - 2, "disabled=\"disabled\""); 
     } 
     return new MvcHtmlString(rawstring); 
    } 

public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly) 
    { 
     string rawstring = htmlString.ToString(); 
     if (@readonly) 
     { 
      rawstring = rawstring.Insert(rawstring.Length - 2, "readonly=\"readonly\""); 
     } 
     return new MvcHtmlString(rawstring); 
    } 

いくつかの拡張メソッドを使用して、その後....

@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsReadonly(x) 
関連する問題