【问题标题】:Has the behavior for DataAnnotations in asp.net mvc 3 changed?asp.net mvc 3 中 DataAnnotations 的行为是否发生了变化?
【发布时间】:2011-11-20 13:01:13
【问题描述】:

我有一个带有属性的模型

[ReadOnly(true)]
public decimal BodyMassIndex { get; private set; }

当我打电话时在我的视图中

@Html.EditorForModel()

我仍然得到该属性的标准可编辑文本框

这是为什么?如果文本框仍然是可编辑的,那么这个 DataAnnotation 属性的意义何在?

Brad Wilson's post

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 data-annotations mvc-editor-templates


    【解决方案1】:

    这不是 DataAnnotation 属性。请注意,它位于 System.ComponentModel 命名空间中。数据注释位于 System.ComponentModel.DataAnnotations 命名空间中。

    但是,在这种情况下,我们可以考虑支持它。但是您到底期望会发生什么?为什么要这样做?

    【讨论】:

    • 好吧,这个例子是针对一个 PhysicalTest ViewModel。该表单应该显示重量和高度的文本框。 BodyMassIndex 根本不应该是输入,但我确实希望用户知道 BodyMassIndex(根据体重和身高计算得出)......我只想使用 EditorForModel 而不必创建自定义 EditorTemplate。 .. 想象一个具有两个输入文本字段的表单,然后是一个 BodyMAssIndex 标签,一旦这两个值中的任何一个发生变化,它就会发生变化。
    • 从您的回复来看,我可以告诉我没有正确使用此属性:s。您介意指出此属性的正常用法吗?
    【解决方案2】:

    你可以使用

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

    【讨论】:

    • 这可行,但我想使用 EditorForModel 并为此定义一个自定义 EditorTemplate 似乎有点过头了。我仍然不确定 ReadOnlyAttribute 的目的和普通用法是什么
    【解决方案3】:

    根据我对您的问题和其他答案的 cmets 的了解,您只是想显示 BodyMassIndex,而不是使其可编辑。

    如果是这种情况,请使用@Html.DisplayFor 而不是@Html.EditorFor

    【讨论】:

      【解决方案4】:

      AFAIK ReadOnlyAttribute 用于类的属性。 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.
      

      所以你在你的类中使用它来防止修改属性。 (至少我赋予该属性的含义)

      如果你想要一个只读的文本框,请使用类似的东西

       @Html.TextBox("MyText", "my text", new { @readonly="readonly" })
      

      @first of readonly 告诉编译器绕过保留字

      【讨论】:

        【解决方案5】:

        这适用于带有 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>
        

        【讨论】:

          猜你喜欢
          • 2010-09-15
          • 1970-01-01
          • 1970-01-01
          • 2011-12-28
          • 1970-01-01
          • 1970-01-01
          • 2017-04-15
          • 2020-12-03
          • 1970-01-01
          相关资源
          最近更新 更多