Has the behavior for DataAnnotations in asp.net mvc 3 changed?

只谈情不闲聊 提交于 2019-12-06 05:31:30

问题


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


回答1:


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?




回答2:


you can use

@Html.TextBoxFor(x=> x.ModelProperty, new { @readonly="readonly"})



回答3:


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.




回答4:


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




回答5:


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>


来源:https://stackoverflow.com/questions/7476405/has-the-behavior-for-dataannotations-in-asp-net-mvc-3-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!