質問

ユーザーがクライアントアイテムを作成および編集できるUIを担当する、厳密に型指定されたMVCビューコントロールがあります。作成時に ClientId を定義できますが、編集はできません。これをUIに反映します。

このために、次の行があります:

<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new 
 { @readonly = 
   (ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0 
      ? "readonly" : "false") 
 } )
%>

readonly属性にどの値を指定しても(&quot; false&quot;および&quot;&quot;であっても)、FirefoxとIE7は入力を読み取り専用にしているため、直感に反します。属性が不要な場合、属性を完全に削除する、三項演算子ベースの良い方法はありますか?

役に立ちましたか?

解決

難しい問題...ただし、 readonly 属性のみを定義する場合は、次のようにできます。

<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, 
  ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0 
    ? new { @readonly =  "readonly" } 
    : null) 
%>

さらに属性を定義する場合は、2つの匿名タイプを定義し、属性の複数のコピーを作成する必要があります。たとえば、次のようなもの(私はとにかく好きではありません):

ClientId.Length > 0 
  ? (object)new { @readonly = "readonly", @class = "myCSS" } 
  : (object)new { @class = "myCSS" }

他のヒント

複数の属性を定義し、条件付き読み取り専用他の属性を複製しない場合は、 属性に匿名型の代わりに辞書を使用できます。

e.g。

Dictionary<string, object> htmlAttributes = new Dictionary<string, object>();
htmlAttributes.Add("class", "myCSS");
htmlAttributes.Add("data-attr1", "val1");
htmlAttributes.Add("data-attr2", "val2");
if (Model.LoggedInData.IsAdmin == false)
{
    htmlAttributes.Add("readonly", "readonly");
}


@:User: @Html.TextBoxFor(
    m => m.User,
    htmlAttributes)  

別の方法は、単純に古いHTMLとして出力することです。はい、エディターはあなたを間違っていると思わせますが、VS2008SP1では頻繁に起こるようです。この例は、CTP5で完全に無駄になっているように見えるチェックボックス専用ですが、条件付き属性を出力する方法のアイデアを提供します。

<input type="checkbox" name="roles" value='<%# Eval("Name") %>' 
  <%# ((bool) Eval("InRole")) ? "checked" : "" %> 
  <%# ViewData.Model.IsInRole("Admin") ? "" : "disabled" %> />

ヒント:ブラウザーで要素を読み取り専用または無効にするreadonly / disabled属性が存在するだけです。

@Html.TextBoxFor(x => x.Name, isReadonly ?(object) new { @readonly = true } : new { /*Some other attributes*/ })

そうすべきだと思う

<%= ((bool) Eval("InRole")) ? "checked" : "" %> 

代わりにlepyiesの回答。

<%# ((bool) Eval("InRole")) ? "checked" : "" %> 

少なくとも#では機能しませんでしたが、=では機能しました。私は何か間違ったことをしましたか?とにかくヒントをありがとう:)

$(function(){   $(&quot; [readonly = 'false']&quot;)。removeAttr(&quot; readonly&quot;);  });

iを使用:

   @Html.TextAreaFor(model => model.ComentarioGestor, comentarioGestor? new { @class = "form-control" } : new { @class = "form-control", @readonly = "readonly" } as object)

上記の提案のほとんどを試してみましたが、今では1行で最も単純なものに到達しました。 2つの匿名HTML属性オブジェクトを結合するには、その1つを「オブジェクト」として宣言します。タイプ。

@Html.TextBoxFor(m => m.Email, !isEdit ? new { id = "email_box" } : new { id = "email_box", @readonly = isEdit ? "readonly" : "false" } as object)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top