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