Asp.net mvc asp.net mvc 3中DataAnnotation的行为是否已更改?
我有一个带属性的模型Asp.net mvc asp.net mvc 3中DataAnnotation的行为是否已更改?,asp.net-mvc,asp.net-mvc-3,data-annotations,mvc-editor-templates,Asp.net Mvc,Asp.net Mvc 3,Data Annotations,Mvc Editor Templates,我有一个带属性的模型 [ReadOnly(true)] public decimal BodyMassIndex { get; private set; } 在我看来,当我打电话时 @Html.EditorForModel() 我仍然可以得到该属性的标准可编辑文本框 为什么会这样?如果文本框仍然可编辑,那么此DataAnnotation属性有什么意义 好的,ReadOnlyAttribute是类的属性 因此,您可以在类中使用它来防止修改属性。(至少是我赋予该属性的含义) 如果您想要文本框只读
[ReadOnly(true)]
public decimal BodyMassIndex { get; private set; }
在我看来,当我打电话时
@Html.EditorForModel()
我仍然可以得到该属性的标准可编辑文本框
为什么会这样?如果文本框仍然可编辑,那么此DataAnnotation属性有什么意义
好的,ReadOnlyAttribute是类的属性 因此,您可以在类中使用它来防止修改属性。(至少是我赋予该属性的含义) 如果您想要文本框只读,请使用类似的内容
@Html.TextBox("MyText", "my text", new { @readonly="readonly" })
@first of readonly告诉编译器使用您可以使用的保留字
@Html.TextBoxFor(x=> x.ModelProperty, new { @readonly="readonly"})
这不是DataAnnotation属性。请注意,它位于System.ComponentModel名称空间中。数据注释位于System.ComponentModel.DataAnnotations命名空间中
然而,这是一个我们可以考虑支持它的情况。但您到底希望发生什么?为什么要这样做?根据我对您的问题和其他答案的评论的理解,您只想显示BodyMassIndex,而不是将其作为可编辑的 如果是这种情况,请使用
@Html.DisplayFor
而不是@Html.EditorFor
这在Vs2013 C中使用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>
@LabelFor(model=>model.PasswordHash,htmlAttributes:new{@class=“controllabel col-md-3”})
@EditorFor(model=>model.PasswordHash,new{htmlAttributes=new{@class=“form control”,@readonly=“readonly”})
@Html.ValidationMessageFor(model=>model.PasswordHash,“,new{@class=“text danger”})
这个例子是针对PhysicalTest ViewModel的。表单应该显示体重和身高的文本框。BodyMassIndex根本不应该是一个输入,但我确实希望用户知道BodyMassIndex(根据体重和身高计算)。。。。。。我只想使用EditorForModel,而不必创建自定义EditorTemplate。。。假设一个表单有两个输入文本字段,然后一个BodyMAssIndex标签,当这两个值中的任何一个发生变化时,该标签就会发生变化。根据您的回答,我可以告诉您我没有正确使用此属性:s。您介意指出此属性的正常用法吗?这会起作用,但我想使用EditorForModel并定义一个自定义属性EditorTemplate只是为了这个似乎有点过头了。。另外,我仍然不确定ReadOnlyAttribute的用途和一般用法是什么
<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>