I have a Model with a property
[ReadOnly(true)]
public decimal BodyMassIndex { get; private set; }
In my View when I call
@Html.EditorForModel()
I still get a standard editable textbox for that property
Why is this? if the textbox is still editable whats the point of this DataAnnotation Attibute?
Brad Wilson's post
That is not a DataAnnotation attribute. Notice it's in the System.ComponentModel namespace. Data Annotations are in the System.ComponentModel.DataAnnotations namespace.
However, this is a case where we could consider supporting it. But what exactly did you expect to happen and why do you want this?
you can use
@Html.TextBoxFor(x=> x.ModelProperty, new { @readonly="readonly"})
From what I understand of your question and the comments on other answers, you simply want to display the BodyMassIndex, not have it as editable.
If this is the case, use @Html.DisplayFor
rather than @Html.EditorFor
.
AFAIK the ReadOnlyAttribute is for property of class. From 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.
So you use this inside your classes to prevent modification to the properties. (at least the meaning I give to that attribute)
If you want a textbox readonly use something like that
@Html.TextBox("MyText", "my text", new { @readonly="readonly" })
the @ first of readonly tell the compiler to bybass the reserved word
This works in Vs2013 C# with Bootstrap 3.
<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>