プロパティを持つモデルがあります
[ReadOnly(true)]
public decimal BodyMassIndex { get; private set; }
私が呼び出すときの私のビューで
@Html.EditorForModel()
そのプロパティの標準の編集可能なテキストボックスを引き続き取得します
どうしてこれなの?テキストボックスがまだ編集可能な場合、この DataAnnotation 属性のポイントは何ですか?
プロパティを持つモデルがあります
[ReadOnly(true)]
public decimal BodyMassIndex { get; private set; }
私が呼び出すときの私のビューで
@Html.EditorForModel()
そのプロパティの標準の編集可能なテキストボックスを引き続き取得します
どうしてこれなの?テキストボックスがまだ編集可能な場合、この DataAnnotation 属性のポイントは何ですか?
それは DataAnnotation 属性ではありません。System.ComponentModel名前空間にあることに注意してください。データ注釈はSystem.ComponentModel.DataAnnotations名前空間にあります。
ただし、これはサポートを検討できるケースです。しかし、正確には何が起こると予想していたのでしょうか? なぜこれが必要なのですか?
私の知る限り、ReadOnlyAttribute はクラスのプロパティ用です。MSDN から
Members that are marked with the ReadOnlyAttribute set to true or that do not have a Set method
cannot be changed. Members that do not have this attribute or that are marked with the
ReadOnlyAttribute set to false are read/write, and they can be changed. The default is No.
したがって、これをクラス内で使用して、プロパティの変更を防ぎます。(少なくとも私がその属性に与える意味)
テキストボックスを読み取り専用にしたい場合は、そのようなものを使用してください
@Html.TextBox("MyText", "my text", new { @readonly="readonly" })
readonly の最初の @ は、予約語をバイパスするようにコンパイラに指示します
あなたの質問と他の回答に対するコメントについて私が理解していることから、BodyMassIndex を編集可能にするのではなく、表示したいだけです。
この場合、 では@Html.DisplayFor
なくを使用して@Html.EditorFor
ください。
あなたが使用することができます
@Html.TextBoxFor(x=> x.ModelProperty, new { @readonly="readonly"})
これは、Bootstrap 3 を使用する Vs2013 C# で機能します。
<div class="form-group">
@Html.LabelFor(model => model.PasswordHash, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
@Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { @class = "form-control", @readonly="readonly" } })
@Html.ValidationMessageFor(model => model.PasswordHash, "", new { @class = "text-danger" })
</div>
</div>